From 75b47195927b1cf9f2e33dcb1838acfa675714ec Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Thu, 23 Jan 2020 16:46:15 +0100 Subject: [PATCH 01/27] Implement detector connection factory with protocol detection mechanism Signed-off-by: Ludovic Orban --- .../server/AbstractConnectionFactory.java | 16 + .../jetty/server/ConnectionFactory.java | 40 + .../server/DetectorConnectionFactory.java | 294 +++++ .../server/OptionalSslConnectionFactory.java | 185 +-- .../jetty/server/ProxyConnectionFactory.java | 1046 ++++++++++------- .../jetty/server/SslConnectionFactory.java | 18 +- .../jetty/server/DetectorConnectionTest.java | 715 +++++++++++ .../server/OptionalSslConnectionTest.java | 44 +- .../jetty/server/ProxyConnectionTest.java | 396 +++++-- 9 files changed, 2065 insertions(+), 689 deletions(-) create mode 100644 jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java create mode 100644 jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java index 1b541a70d55..ac7079eea89 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java @@ -20,6 +20,7 @@ package org.eclipse.jetty.server; import java.util.Arrays; import java.util.Collections; +import java.util.Iterator; import java.util.List; import org.eclipse.jetty.io.AbstractConnection; @@ -87,6 +88,21 @@ public abstract class AbstractConnectionFactory extends ContainerLifeCycle imple _inputbufferSize = size; } + protected String findNextProtocol(Connector connector) + { + String nextProtocol = null; + for (Iterator it = connector.getProtocols().iterator(); it.hasNext(); ) + { + String protocol = it.next(); + if (getProtocol().equalsIgnoreCase(protocol)) + { + nextProtocol = it.hasNext() ? it.next() : null; + break; + } + } + return nextProtocol; + } + protected AbstractConnection configure(AbstractConnection connection, Connector connector, EndPoint endPoint) { connection.setInputBufferSize(getInputBufferSize()); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionFactory.java index c8a4b880e56..9bec7cf81a8 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionFactory.java @@ -18,6 +18,7 @@ package org.eclipse.jetty.server; +import java.nio.ByteBuffer; import java.util.List; import org.eclipse.jetty.http.BadMessageException; @@ -85,4 +86,43 @@ public interface ConnectionFactory */ Connection upgradeConnection(Connector connector, EndPoint endPoint, MetaData.Request upgradeRequest, HttpFields responseFields) throws BadMessageException; } + + /** + *

Connections created by this factory MUST implement {@link Connection.UpgradeTo}.

+ */ + interface Detecting extends ConnectionFactory + { + /** + * The possible outcomes of the {@link #detect(ByteBuffer)} method. + */ + enum Detection + { + /** + * A {@link Detecting} can work with the given bytes. + */ + RECOGNIZED, + /** + * A {@link Detecting} cannot work with the given bytes. + */ + NOT_RECOGNIZED, + /** + * A {@link Detecting} requires more bytes to make a decision. + */ + NEED_MORE_BYTES + } + + /** + *

Check the bytes in the given {@code buffer} to figure out if this {@link Detecting} instance + * can work with them or not.

+ *

The {@code buffer} MUST be left untouched by this method: bytes MUST NOT be consumed and MUST NOT be modified.

+ * @param buffer the buffer. + * @return One of: + *
    + *
  • {@link Detection#RECOGNIZED} if this {@link Detecting} instance can work with the bytes in the buffer
  • + *
  • {@link Detection#NOT_RECOGNIZED} if this {@link Detecting} instance cannot work with the bytes in the buffer
  • + *
  • {@link Detection#NEED_MORE_BYTES} if this {@link Detecting} instance requires more bytes to make a decision
  • + *
+ */ + Detection detect(ByteBuffer buffer); + } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java new file mode 100644 index 00000000000..0332329ab9b --- /dev/null +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java @@ -0,0 +1,294 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.server; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.stream.Collectors; + +import org.eclipse.jetty.io.AbstractConnection; +import org.eclipse.jetty.io.Connection; +import org.eclipse.jetty.io.EndPoint; +import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.log.Log; +import org.eclipse.jetty.util.log.Logger; + +/** + * A {@link ConnectionFactory} combining multiple {@link Detecting} instances that will upgrade to + * the first one recognizing the bytes in the buffer. + */ +public class DetectorConnectionFactory extends AbstractConnectionFactory implements ConnectionFactory.Detecting +{ + private static final Logger LOG = Log.getLogger(DetectorConnectionFactory.class); + + private final List _detectingConnectionFactories; + + /** + *

When the first bytes are not recognized by the {@code detectingConnectionFactories}, the default behavior is to + * upgrade to the protocol returned by {@link #findNextProtocol(Connector)}.

+ * @param detectingConnectionFactories the {@link Detecting} instances. + */ + public DetectorConnectionFactory(Detecting... detectingConnectionFactories) + { + super(toProtocolString(detectingConnectionFactories)); + _detectingConnectionFactories = Arrays.asList(detectingConnectionFactories); + for (Detecting detectingConnectionFactory : detectingConnectionFactories) + { + addBean(detectingConnectionFactory); + } + } + + private static String toProtocolString(Detecting... detectingConnectionFactories) + { + if (detectingConnectionFactories.length == 0) + throw new IllegalArgumentException("At least one detecting instance is required"); + + // remove protocol duplicates while keeping their ordering -> use LinkedHashSet + LinkedHashSet protocols = Arrays.stream(detectingConnectionFactories).map(ConnectionFactory::getProtocol).collect(Collectors.toCollection(LinkedHashSet::new)); + + String protocol = String.join("|", protocols); + if (LOG.isDebugEnabled()) + LOG.debug("Detector generated protocol name : {}", protocol); + return protocol; + } + + /** + * Performs a detection using multiple {@link ConnectionFactory.Detecting} instances and returns the aggregated outcome. + * @param buffer the buffer to perform a detection against. + * @return A {@link Detecting.Detection} value with the detection outcome of the {@code detectingConnectionFactories}. + */ + @Override + public Detecting.Detection detect(ByteBuffer buffer) + { + if (LOG.isDebugEnabled()) + LOG.debug("Attempting detection from buffer {} using {}", buffer, _detectingConnectionFactories); + boolean needMoreBytes = true; + for (Detecting detectingConnectionFactory : _detectingConnectionFactories) + { + Detecting.Detection detection = detectingConnectionFactory.detect(buffer); + if (detection == Detecting.Detection.RECOGNIZED) + { + if (LOG.isDebugEnabled()) + LOG.debug("Detection recognized bytes from buffer {} using {}", buffer, _detectingConnectionFactories); + return Detecting.Detection.RECOGNIZED; + } + needMoreBytes &= detection == Detection.NEED_MORE_BYTES; + } + if (LOG.isDebugEnabled()) + LOG.debug("Detection {} from buffer {} using {}", (needMoreBytes ? "requires more bytes" : "not recognized"), buffer, _detectingConnectionFactories); + return needMoreBytes ? Detection.NEED_MORE_BYTES : Detection.NOT_RECOGNIZED; + } + + /** + * Utility method that performs an upgrade to the specified connection factory, disposing of the given resources when needed. + * @param connectionFactory the connection factory to upgrade to. + * @param connector the connector. + * @param endPoint the endpoint. + */ + protected static void upgradeToConnectionFactory(ConnectionFactory connectionFactory, Connector connector, EndPoint endPoint) throws IllegalStateException + { + if (LOG.isDebugEnabled()) + LOG.debug("Upgrading to connection factory {}", connectionFactory); + if (connectionFactory == null) + throw new IllegalStateException("Cannot upgrade: connection factory must not be null for " + endPoint); + Connection nextConnection = connectionFactory.newConnection(connector, endPoint); + if (!(nextConnection instanceof Connection.UpgradeTo)) + throw new IllegalStateException("Cannot upgrade: " + nextConnection + " does not implement " + Connection.UpgradeTo.class.getName() + " for " + endPoint); + endPoint.upgrade(nextConnection); + if (LOG.isDebugEnabled()) + LOG.debug("Upgraded to connection factory {} and released buffer", connectionFactory); + } + + /** + *

Callback method called when detection was unsuccessful. + * This implementation upgrades to the protocol returned by {@link #findNextProtocol(Connector)}.

+ * @param connector the connector. + * @param endPoint the endpoint. + * @param buffer the buffer. + */ + protected void nextProtocol(Connector connector, EndPoint endPoint, ByteBuffer buffer) throws IllegalStateException + { + String nextProtocol = findNextProtocol(connector); + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} detection unsuccessful, found '{}' as the next protocol to upgrade to", getProtocol(), nextProtocol); + if (nextProtocol == null) + throw new IllegalStateException("Cannot find protocol following '" + getProtocol() + "' in connector's protocol list " + connector.getProtocols() + " for " + endPoint); + upgradeToConnectionFactory(connector.getConnectionFactory(nextProtocol), connector, endPoint); + } + + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) + { + return configure(new DetectorConnection(endPoint, connector), connector, endPoint); + } + + private class DetectorConnection extends AbstractConnection implements Connection.UpgradeFrom, Connection.UpgradeTo + { + private final Connector _connector; + private final ByteBuffer _buffer; + + private DetectorConnection(EndPoint endp, Connector connector) + { + super(endp, connector.getExecutor()); + _connector = connector; + _buffer = connector.getByteBufferPool().acquire(getInputBufferSize(), true); + } + + @Override + public void onUpgradeTo(ByteBuffer prefilled) + { + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} copying prefilled buffer {}", getProtocol(), BufferUtil.toDetailString(prefilled)); + if (BufferUtil.hasContent(prefilled)) + BufferUtil.append(_buffer, prefilled); + } + + @Override + public ByteBuffer onUpgradeFrom() + { + return _buffer; + } + + @Override + public void onOpen() + { + super.onOpen(); + if (!detectAndUpgrade()) + fillInterested(); + } + + @Override + public void onFillable() + { + try + { + while (BufferUtil.space(_buffer) > 0) + { + // Read data + int fill = getEndPoint().fill(_buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} filled buffer with {} bytes", getProtocol(), fill); + if (fill < 0) + { + _connector.getByteBufferPool().release(_buffer); + getEndPoint().shutdownOutput(); + return; + } + if (fill == 0) + { + fillInterested(); + return; + } + + if (detectAndUpgrade()) + return; + } + + // all Detecting instances want more bytes than this buffer can store + LOG.warn("Detector {} failed to detect upgrade target on {} for {}", getProtocol(), _detectingConnectionFactories, getEndPoint()); + releaseAndClose(); + } + catch (Throwable x) + { + LOG.warn("Detector {} error for {}", getProtocol(), getEndPoint(), x); + releaseAndClose(); + } + } + + /** + * @return true when upgrade was performed, false otherwise. + */ + private boolean detectAndUpgrade() + { + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} performing detection with {} bytes", getProtocol(), _buffer.remaining()); + boolean notRecognized = true; + for (Detecting detectingConnectionFactory : _detectingConnectionFactories) + { + Detecting.Detection detection = detectingConnectionFactory.detect(_buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} performed detection from {} with {} which returned {}", getProtocol(), BufferUtil.toDetailString(_buffer), detectingConnectionFactory, detection); + if (detection == Detecting.Detection.RECOGNIZED) + { + try + { + // This DetectingConnectionFactory recognized those bytes -> upgrade to the next one. + Connection nextConnection = detectingConnectionFactory.newConnection(_connector, getEndPoint()); + if (!(nextConnection instanceof UpgradeTo)) + throw new IllegalStateException("Cannot upgrade: " + nextConnection + " does not implement " + UpgradeTo.class.getName()); + getEndPoint().upgrade(nextConnection); + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} upgraded to {}", getProtocol(), nextConnection); + return true; + } + catch (DetectionFailureException e) + { + // It's just bubbling up from a nested Detector, so it's already handled, just rethrow it. + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} failed to upgrade, rethrowing", getProtocol(), e); + throw e; + } + catch (Exception e) + { + // Two reasons that can make us end up here: + // 1) detectingConnectionFactory.newConnection() failed? probably because it cannot find the next protocol + // 2) nextConnection is not instanceof UpgradeTo + // -> release the resources before rethrowing as DetectionFailureException + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} failed to upgrade", getProtocol()); + releaseAndClose(); + throw new DetectionFailureException(e); + } + } + notRecognized &= detection == Detecting.Detection.NOT_RECOGNIZED; + } + + if (notRecognized) + { + // No DetectingConnectionFactory recognized those bytes -> call unsuccessful detection callback. + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} failed to detect a known protocol, falling back to nextProtocol()", getProtocol()); + nextProtocol(_connector, getEndPoint(), _buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} call to nextProtocol() succeeded, assuming upgrade performed", getProtocol()); + return true; + } + + return false; + } + + private void releaseAndClose() + { + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} releasing buffer and closing", getProtocol()); + _connector.getByteBufferPool().release(_buffer); + close(); + } + } + + private static class DetectionFailureException extends RuntimeException + { + public DetectionFailureException(Throwable cause) + { + super(cause); + } + } +} diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/OptionalSslConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/OptionalSslConnectionFactory.java index 03d931ed75d..a2a049be011 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/OptionalSslConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/OptionalSslConnectionFactory.java @@ -18,14 +18,10 @@ package org.eclipse.jetty.server; -import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import org.eclipse.jetty.io.AbstractConnection; -import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; @@ -34,62 +30,70 @@ import org.eclipse.jetty.util.log.Logger; *

A ConnectionFactory whose connections detect whether the first bytes are * TLS bytes and upgrades to either a TLS connection or to another configurable * connection.

+ * + * @deprecated Use {@link DetectorConnectionFactory} with a {@link SslConnectionFactory} instead. */ -public class OptionalSslConnectionFactory extends AbstractConnectionFactory +@Deprecated +public class OptionalSslConnectionFactory extends DetectorConnectionFactory { - private static final Logger LOG = Log.getLogger(OptionalSslConnection.class); - private static final int TLS_ALERT_FRAME_TYPE = 0x15; - private static final int TLS_HANDSHAKE_FRAME_TYPE = 0x16; - private static final int TLS_MAJOR_VERSION = 3; - - private final SslConnectionFactory sslConnectionFactory; - private final String otherProtocol; + private static final Logger LOG = Log.getLogger(OptionalSslConnectionFactory.class); + private final String _nextProtocol; /** *

Creates a new ConnectionFactory whose connections can upgrade to TLS or another protocol.

- *

If {@code otherProtocol} is {@code null}, and the first bytes are not TLS, then - * {@link #otherProtocol(ByteBuffer, EndPoint)} is called.

* - * @param sslConnectionFactory The SslConnectionFactory to use if the first bytes are TLS - * @param otherProtocol the protocol of the ConnectionFactory to use if the first bytes are not TLS, + * @param sslConnectionFactory The {@link SslConnectionFactory} to use if the first bytes are TLS + * @param nextProtocol the protocol of the {@link ConnectionFactory} to use if the first bytes are not TLS, * or null to explicitly handle the non-TLS case */ - public OptionalSslConnectionFactory(SslConnectionFactory sslConnectionFactory, String otherProtocol) + public OptionalSslConnectionFactory(SslConnectionFactory sslConnectionFactory, String nextProtocol) { - super("ssl|other"); - this.sslConnectionFactory = sslConnectionFactory; - this.otherProtocol = otherProtocol; - } - - @Override - public Connection newConnection(Connector connector, EndPoint endPoint) - { - return configure(new OptionalSslConnection(endPoint, connector), connector, endPoint); + super(sslConnectionFactory); + _nextProtocol = nextProtocol; } /** - * @param buffer The buffer with the first bytes of the connection - * @return whether the bytes seem TLS bytes - */ - protected boolean seemsTLS(ByteBuffer buffer) - { - int tlsFrameType = buffer.get(0) & 0xFF; - int tlsMajorVersion = buffer.get(1) & 0xFF; - return (tlsFrameType == TLS_HANDSHAKE_FRAME_TYPE || tlsFrameType == TLS_ALERT_FRAME_TYPE) && tlsMajorVersion == TLS_MAJOR_VERSION; - } - - /** - *

Callback method invoked when {@code otherProtocol} is {@code null} - * and the first bytes are not TLS.

+ *

Callback method invoked when the detected bytes are not TLS.

*

This typically happens when a client is trying to connect to a TLS * port using the {@code http} scheme (and not the {@code https} scheme).

* + * @param connector The connector object + * @param endPoint The connection EndPoint object + * @param buffer The buffer with the first bytes of the connection + */ + protected void nextProtocol(Connector connector, EndPoint endPoint, ByteBuffer buffer) + { + if (LOG.isDebugEnabled()) + LOG.debug("OptionalSSL TLS detection unsuccessful, attempting to upgrade to {}", _nextProtocol); + if (_nextProtocol != null) + { + ConnectionFactory connectionFactory = connector.getConnectionFactory(_nextProtocol); + if (connectionFactory == null) + throw new IllegalStateException("Cannot find protocol '" + _nextProtocol + "' in connector's protocol list " + connector.getProtocols() + " for " + endPoint); + upgradeToConnectionFactory(connectionFactory, connector, endPoint); + } + else + { + otherProtocol(buffer, endPoint); + } + } + + /** + *

Legacy callback method invoked when {@code nextProtocol} is {@code null} + * and the first bytes are not TLS.

+ *

This typically happens when a client is trying to connect to a TLS + * port using the {@code http} scheme (and not the {@code https} scheme).

+ *

This method is kept around for backward compatibility.

+ * * @param buffer The buffer with the first bytes of the connection * @param endPoint The connection EndPoint object - * @see #seemsTLS(ByteBuffer) + * @deprecated Override {@link #nextProtocol(Connector, EndPoint, ByteBuffer)} instead. */ + @Deprecated protected void otherProtocol(ByteBuffer buffer, EndPoint endPoint) { + LOG.warn("Detected non-TLS bytes, but no other protocol to upgrade to for {}", endPoint); + // There are always at least 2 bytes. int byte1 = buffer.get(0) & 0xFF; int byte2 = buffer.get(1) & 0xFF; @@ -122,105 +126,4 @@ public class OptionalSslConnectionFactory extends AbstractConnectionFactory endPoint.close(); } } - - private class OptionalSslConnection extends AbstractConnection implements Connection.UpgradeFrom - { - private final Connector connector; - private final ByteBuffer buffer; - - public OptionalSslConnection(EndPoint endPoint, Connector connector) - { - super(endPoint, connector.getExecutor()); - this.connector = connector; - this.buffer = BufferUtil.allocateDirect(1536); - } - - @Override - public void onOpen() - { - super.onOpen(); - fillInterested(); - } - - @Override - public void onFillable() - { - try - { - while (true) - { - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - // Always have at least 2 bytes. - if (BufferUtil.length(buffer) >= 2) - { - upgrade(buffer); - break; - } - } - else if (filled == 0) - { - fillInterested(); - break; - } - else - { - close(); - break; - } - } - } - catch (IOException x) - { - LOG.warn(x); - close(); - } - } - - @Override - public ByteBuffer onUpgradeFrom() - { - return buffer; - } - - private void upgrade(ByteBuffer buffer) - { - if (LOG.isDebugEnabled()) - LOG.debug("Read {}", BufferUtil.toDetailString(buffer)); - - EndPoint endPoint = getEndPoint(); - if (seemsTLS(buffer)) - { - if (LOG.isDebugEnabled()) - LOG.debug("Detected TLS bytes, upgrading to {}", sslConnectionFactory); - endPoint.upgrade(sslConnectionFactory.newConnection(connector, endPoint)); - } - else - { - if (otherProtocol != null) - { - ConnectionFactory connectionFactory = connector.getConnectionFactory(otherProtocol); - if (connectionFactory != null) - { - if (LOG.isDebugEnabled()) - LOG.debug("Detected non-TLS bytes, upgrading to {}", connectionFactory); - Connection next = connectionFactory.newConnection(connector, endPoint); - endPoint.upgrade(next); - } - else - { - LOG.warn("Missing {} {} in {}", otherProtocol, ConnectionFactory.class.getSimpleName(), connector); - close(); - } - } - else - { - if (LOG.isDebugEnabled()) - LOG.debug("Detected non-TLS bytes, but no other protocol to upgrade to"); - otherProtocol(buffer, endPoint); - } - } - } - } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java index 782334faac7..d895e120055 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java @@ -27,7 +27,6 @@ import java.nio.ByteBuffer; import java.nio.channels.ReadPendingException; import java.nio.channels.WritePendingException; import java.nio.charset.StandardCharsets; -import java.util.Iterator; import org.eclipse.jetty.io.AbstractConnection; import org.eclipse.jetty.io.Connection; @@ -46,252 +45,280 @@ import org.eclipse.jetty.util.log.Logger; * * @see http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt */ -public class ProxyConnectionFactory extends AbstractConnectionFactory +public class ProxyConnectionFactory extends DetectorConnectionFactory { - private static final Logger LOG = Log.getLogger(ProxyConnectionFactory.class); public static final String TLS_VERSION = "TLS_VERSION"; + private static final Logger LOG = Log.getLogger(ProxyConnectionFactory.class); - private final String _next; - private int _maxProxyHeader = 1024; - - /** - * Proxy Connection Factory that uses the next ConnectionFactory - * on the connector as the next protocol - */ public ProxyConnectionFactory() { - super("proxy"); - _next = null; + this(null); } public ProxyConnectionFactory(String nextProtocol) { - super("proxy"); - _next = nextProtocol; + super(new ProxyV1ConnectionFactory(nextProtocol), new ProxyV2ConnectionFactory(nextProtocol)); + } + + private static ConnectionFactory findNextConnectionFactory(String nextProtocol, Connector connector, AbstractConnectionFactory currentConnectionFactory, EndPoint endp) + { + if (LOG.isDebugEnabled()) + LOG.debug("finding next connection factory for protocol {}", nextProtocol); + String nextProtocolToFind = nextProtocol; + if (nextProtocol == null) + nextProtocolToFind = currentConnectionFactory.findNextProtocol(connector); + if (nextProtocolToFind == null) + throw new IllegalStateException("Cannot find protocol following '" + currentConnectionFactory.getProtocol() + "' in connector's protocol list " + connector.getProtocols() + " for " + endp); + ConnectionFactory connectionFactory = connector.getConnectionFactory(nextProtocolToFind); + if (connectionFactory == null) + throw new IllegalStateException("Cannot find protocol '" + nextProtocol + "' in connector's protocol list " + connector.getProtocols() + " for " + endp); + if (LOG.isDebugEnabled()) + LOG.debug("found next connection factory {} for protocol {}", connectionFactory, nextProtocol); + return connectionFactory; } public int getMaxProxyHeader() { - return _maxProxyHeader; + ProxyV2ConnectionFactory v2 = getBean(ProxyV2ConnectionFactory.class); + return v2.getMaxProxyHeader(); } public void setMaxProxyHeader(int maxProxyHeader) { - _maxProxyHeader = maxProxyHeader; + ProxyV2ConnectionFactory v2 = getBean(ProxyV2ConnectionFactory.class); + v2.setMaxProxyHeader(maxProxyHeader); } - @Override - public Connection newConnection(Connector connector, EndPoint endp) + private static class ProxyV1ConnectionFactory extends AbstractConnectionFactory implements Detecting { - String next = _next; - if (next == null) + private static final byte[] SIGNATURE = "PROXY".getBytes(StandardCharsets.US_ASCII); + + private final String _nextProtocol; + + private ProxyV1ConnectionFactory(String nextProtocol) { - for (Iterator i = connector.getProtocols().iterator(); i.hasNext(); ) - { - String p = i.next(); - if (getProtocol().equalsIgnoreCase(p)) - { - next = i.next(); - break; - } - } - } - - return new ProxyProtocolV1orV2Connection(endp, connector, next); - } - - public class ProxyProtocolV1orV2Connection extends AbstractConnection - { - // Only do a tiny read to figure out what PROXY version it is. - private final ByteBuffer _buffer = BufferUtil.allocate(16); - private final Connector _connector; - private final String _next; - - protected ProxyProtocolV1orV2Connection(EndPoint endp, Connector connector, String next) - { - super(endp, connector.getExecutor()); - _connector = connector; - _next = next; + super("proxy"); + this._nextProtocol = nextProtocol; } @Override - public void onOpen() + public Detection detect(ByteBuffer buffer) { - super.onOpen(); - fillInterested(); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 attempting detection with {} bytes", buffer.remaining()); + if (buffer.remaining() < SIGNATURE.length) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 detection requires more bytes"); + return Detection.NEED_MORE_BYTES; + } + + for (int i = 0; i < SIGNATURE.length; i++) + { + byte signatureByte = SIGNATURE[i]; + byte byteInBuffer = buffer.get(i); + if (byteInBuffer != signatureByte) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 detection unsuccessful"); + return Detection.NOT_RECOGNIZED; + } + } + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 detection succeeded"); + return Detection.RECOGNIZED; } @Override - public void onFillable() + public Connection newConnection(Connector connector, EndPoint endp) { - try + ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, this, endp); + return configure(new ProxyProtocolV1Connection(endp, connector, nextConnectionFactory), connector, endp); + } + + private static class ProxyProtocolV1Connection extends AbstractConnection implements Connection.UpgradeFrom, Connection.UpgradeTo + { + // 0 1 2 3 4 5 6 + // 98765432109876543210987654321 + // PROXY P R.R.R.R L.L.L.L R Lrn + + private final Connector _connector; + private final ConnectionFactory _next; + private final ByteBuffer _buffer; + private final StringBuilder _builder = new StringBuilder(); + private final String[] _fields = new String[6]; + private int _index; + private int _length; + + private ProxyProtocolV1Connection(EndPoint endp, Connector connector, ConnectionFactory next) { - while (BufferUtil.space(_buffer) > 0) + super(endp, connector.getExecutor()); + _connector = connector; + _next = next; + _buffer = _connector.getByteBufferPool().acquire(getInputBufferSize(), true); + } + + @Override + public void onFillable() + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 onFillable current index = ", _index); + try { - // Read data - int fill = getEndPoint().fill(_buffer); - if (fill < 0) + while (_index < 7) { - getEndPoint().shutdownOutput(); - return; + // Read data + int fill = getEndPoint().fill(_buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 filled buffer with {} bytes", fill); + if (fill < 0) + { + _connector.getByteBufferPool().release(_buffer); + getEndPoint().shutdownOutput(); + return; + } + if (fill == 0) + { + fillInterested(); + return; + } + + if (parse()) + break; } - if (fill == 0) + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 onFillable parsing done, now upgrading"); + upgrade(); + } + catch (Throwable x) + { + LOG.warn("Proxy v1 error for {}", getEndPoint(), x); + releaseAndClose(); + } + } + + @Override + public void onOpen() + { + super.onOpen(); + + try + { + while (_index < 7) { - fillInterested(); - return; + if (!parse()) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 onOpen parsing ran out of bytes, marking as fillInterested"); + fillInterested(); + return; + } + } + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 onOpen parsing done, now upgrading"); + upgrade(); + } + catch (Throwable x) + { + LOG.warn("Proxy v1 error for {}", getEndPoint(), x); + releaseAndClose(); + } + } + + @Override + public ByteBuffer onUpgradeFrom() + { + return _buffer; + } + + @Override + public void onUpgradeTo(ByteBuffer prefilled) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 copying prefilled buffer {}", prefilled); + if (BufferUtil.hasContent(prefilled)) + BufferUtil.append(_buffer, prefilled); + } + + /** + * @return true when parsing is done, false when more bytes are needed. + */ + private boolean parse() throws IOException + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 parsing {}", BufferUtil.toDetailString(_buffer)); + _length += _buffer.remaining(); + + // Parse fields + while (_buffer.hasRemaining()) + { + byte b = _buffer.get(); + if (_index < 6) + { + if (b == ' ' || b == '\r') + { + _fields[_index++] = _builder.toString(); + _builder.setLength(0); + if (b == '\r') + _index = 6; + } + else if (b < ' ') + { + throw new IOException("Proxy v1 bad character " + (b & 0xFF)); + } + else + { + _builder.append((char)b); + } + } + else + { + if (b == '\n') + { + _index = 7; + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 parsing is done"); + return true; + } + + throw new IOException("Proxy v1 bad CRLF " + (b & 0xFF)); } } - // Is it a V1? - switch (_buffer.get(0)) - { - case 'P': - { - ProxyProtocolV1Connection v1 = new ProxyProtocolV1Connection(getEndPoint(), _connector, _next, _buffer); - getEndPoint().upgrade(v1); - return; - } - case 0x0D: - { - ProxyProtocolV2Connection v2 = new ProxyProtocolV2Connection(getEndPoint(), _connector, _next, _buffer); - getEndPoint().upgrade(v2); - return; - } - default: - { - LOG.warn("Not PROXY protocol for {}", getEndPoint()); - close(); - break; - } - } + // Not enough bytes. + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 parsing requires more bytes"); + return false; } - catch (Throwable x) + + private void releaseAndClose() { - LOG.warn("PROXY error for " + getEndPoint(), x); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 releasing buffer and closing"); + _connector.getByteBufferPool().release(_buffer); close(); } - } - } - public static class ProxyProtocolV1Connection extends AbstractConnection - { - // 0 1 2 3 4 5 6 - // 98765432109876543210987654321 - // PROXY P R.R.R.R L.L.L.L R Lrn - - private static final int[] SIZE = {29, 23, 21, 13, 5, 3, 1}; - private final Connector _connector; - private final String _next; - private final StringBuilder _builder = new StringBuilder(); - private final String[] _fields = new String[6]; - private int _index; - private int _length; - - protected ProxyProtocolV1Connection(EndPoint endp, Connector connector, String next, ByteBuffer buffer) - { - super(endp, connector.getExecutor()); - _connector = connector; - _next = next; - _length = buffer.remaining(); - parse(buffer); - } - - @Override - public void onOpen() - { - super.onOpen(); - fillInterested(); - } - - private boolean parse(ByteBuffer buffer) - { - // Parse fields - while (buffer.hasRemaining()) + private void upgrade() { - byte b = buffer.get(); - if (_index < 6) + int proxyLineLength = _length - _buffer.remaining(); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v1 pre-upgrade packet length (including CRLF) is {}", proxyLineLength); + if (proxyLineLength >= 110) { - if (b == ' ' || b == '\r') - { - _fields[_index++] = _builder.toString(); - _builder.setLength(0); - if (b == '\r') - _index = 6; - } - else if (b < ' ') - { - LOG.warn("Bad character {} for {}", b & 0xFF, getEndPoint()); - close(); - return false; - } - else - { - _builder.append((char)b); - } - } - else - { - if (b == '\n') - { - _index = 7; - return true; - } - - LOG.warn("Bad CRLF for {}", getEndPoint()); - close(); - return false; - } - } - return true; - } - - @Override - public void onFillable() - { - try - { - ByteBuffer buffer = null; - while (_index < 7) - { - // Create a buffer that will not read too much data - // since once read it is impossible to push back for the - // real connection to read it. - int size = Math.max(1, SIZE[_index] - _builder.length()); - if (buffer == null || buffer.capacity() != size) - buffer = BufferUtil.allocate(size); - else - BufferUtil.clear(buffer); - - // Read data - int fill = getEndPoint().fill(buffer); - if (fill < 0) - { - getEndPoint().shutdownOutput(); - return; - } - if (fill == 0) - { - fillInterested(); - return; - } - - _length += fill; - if (_length >= 108) - { - LOG.warn("PROXY line too long {} for {}", _length, getEndPoint()); - close(); - return; - } - - if (!parse(buffer)) - return; + LOG.warn("Proxy v1 PROXY line too long {} for {}", proxyLineLength, getEndPoint()); + releaseAndClose(); + return; } // Check proxy if (!"PROXY".equals(_fields[0])) { - LOG.warn("Not PROXY protocol for {}", getEndPoint()); - close(); + LOG.warn("Proxy v1 not PROXY protocol for {}", getEndPoint()); + releaseAndClose(); return; } @@ -311,184 +338,221 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory InetSocketAddress remote = new InetSocketAddress(srcIP, Integer.parseInt(srcPort)); InetSocketAddress local = new InetSocketAddress(dstIP, Integer.parseInt(dstPort)); - // Create the next protocol - ConnectionFactory connectionFactory = _connector.getConnectionFactory(_next); - if (connectionFactory == null) - { - LOG.warn("No next protocol '{}' for {}", _next, getEndPoint()); - close(); - return; - } - if (LOG.isDebugEnabled()) - LOG.warn("Next protocol '{}' for {} r={} l={}", _next, getEndPoint(), remote, local); + LOG.debug("Proxy v1 next protocol '{}' for {} r={} l={}", _next, getEndPoint(), remote, local); EndPoint endPoint = new ProxyEndPoint(getEndPoint(), remote, local); - Connection newConnection = connectionFactory.newConnection(_connector, endPoint); - endPoint.upgrade(newConnection); - } - catch (Throwable x) - { - LOG.warn("PROXY error for " + getEndPoint(), x); - close(); + upgradeToConnectionFactory(_next, _connector, endPoint); } } } - private enum Family + private static class ProxyV2ConnectionFactory extends AbstractConnectionFactory implements Detecting { - UNSPEC, INET, INET6, UNIX - } - - private enum Transport - { - UNSPEC, STREAM, DGRAM - } - - private static final byte[] MAGIC = new byte[]{0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A}; - - public class ProxyProtocolV2Connection extends AbstractConnection - { - private final Connector _connector; - private final String _next; - private final boolean _local; - private final Family _family; - private final Transport _transport; - private final int _length; - private final ByteBuffer _buffer; - - protected ProxyProtocolV2Connection(EndPoint endp, Connector connector, String next, ByteBuffer buffer) throws IOException + private enum Family { - super(endp, connector.getExecutor()); - _connector = connector; - _next = next; + UNSPEC, INET, INET6, UNIX + } - if (buffer.remaining() != 16) - throw new IllegalStateException(); + private enum Transport + { + UNSPEC, STREAM, DGRAM + } + + private static final byte[] SIGNATURE = new byte[] + { + 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A + }; + private final String _nextProtocol; + private int _maxProxyHeader = 1024; + + private ProxyV2ConnectionFactory(String nextProtocol) + { + super("proxy"); + this._nextProtocol = nextProtocol; + } + + @Override + public Detection detect(ByteBuffer buffer) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 attempting detection with {} bytes", buffer.remaining()); + if (buffer.remaining() < SIGNATURE.length) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 detection requires more bytes"); + return Detection.NEED_MORE_BYTES; + } + + for (int i = 0; i < SIGNATURE.length; i++) + { + byte signatureByte = SIGNATURE[i]; + byte byteInBuffer = buffer.get(i); + if (byteInBuffer != signatureByte) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 detection unsuccessful"); + return Detection.NOT_RECOGNIZED; + } + } if (LOG.isDebugEnabled()) - LOG.debug("PROXYv2 header {} for {}", BufferUtil.toHexSummary(buffer), this); + LOG.debug("Proxy v2 detection succeeded"); + return Detection.RECOGNIZED; + } - // struct proxy_hdr_v2 { - // uint8_t sig[12]; /* hex 0D 0A 0D 0A 00 0D 0A 51 55 49 54 0A */ - // uint8_t ver_cmd; /* protocol version and command */ - // uint8_t fam; /* protocol family and address */ - // uint16_t len; /* number of following bytes part of the header */ - // }; - for (byte magic : MAGIC) - { - if (buffer.get() != magic) - throw new IOException("Bad PROXY protocol v2 signature"); - } + public int getMaxProxyHeader() + { + return _maxProxyHeader; + } - int versionAndCommand = 0xff & buffer.get(); - if ((versionAndCommand & 0xf0) != 0x20) - throw new IOException("Bad PROXY protocol v2 version"); - _local = (versionAndCommand & 0xf) == 0x00; - - int transportAndFamily = 0xff & buffer.get(); - switch (transportAndFamily >> 4) - { - case 0: - _family = Family.UNSPEC; - break; - case 1: - _family = Family.INET; - break; - case 2: - _family = Family.INET6; - break; - case 3: - _family = Family.UNIX; - break; - default: - throw new IOException("Bad PROXY protocol v2 family"); - } - - switch (0xf & transportAndFamily) - { - case 0: - _transport = Transport.UNSPEC; - break; - case 1: - _transport = Transport.STREAM; - break; - case 2: - _transport = Transport.DGRAM; - break; - default: - throw new IOException("Bad PROXY protocol v2 family"); - } - - _length = buffer.getChar(); - - if (!_local && (_family == Family.UNSPEC || _family == Family.UNIX || _transport != Transport.STREAM)) - throw new IOException(String.format("Unsupported PROXY protocol v2 mode 0x%x,0x%x", versionAndCommand, transportAndFamily)); - - if (_length > getMaxProxyHeader()) - throw new IOException(String.format("Unsupported PROXY protocol v2 mode 0x%x,0x%x,0x%x", versionAndCommand, transportAndFamily, _length)); - - _buffer = _length > 0 ? BufferUtil.allocate(_length) : BufferUtil.EMPTY_BUFFER; + public void setMaxProxyHeader(int maxProxyHeader) + { + _maxProxyHeader = maxProxyHeader; } @Override - public void onOpen() + public Connection newConnection(Connector connector, EndPoint endp) { - super.onOpen(); - if (_buffer.remaining() == _length) - next(); - else - fillInterested(); + ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, this, endp); + return configure(new ProxyProtocolV2Connection(endp, connector, nextConnectionFactory), connector, endp); } - @Override - public void onFillable() + private class ProxyProtocolV2Connection extends AbstractConnection implements Connection.UpgradeFrom, Connection.UpgradeTo { - try + private static final int HEADER_LENGTH = 16; + + private final Connector _connector; + private final ConnectionFactory _next; + private final ByteBuffer _buffer; + private boolean _local; + private Family _family; + private int _length; + private boolean _headerParsed; + + protected ProxyProtocolV2Connection(EndPoint endp, Connector connector, ConnectionFactory next) { - while (_buffer.remaining() < _length) + super(endp, connector.getExecutor()); + _connector = connector; + _next = next; + _buffer = _connector.getByteBufferPool().acquire(getInputBufferSize(), true); + } + + @Override + public void onUpgradeTo(ByteBuffer prefilled) + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 copying prefilled buffer {}", prefilled); + if (BufferUtil.hasContent(prefilled)) + BufferUtil.append(_buffer, prefilled); + } + + @Override + public void onOpen() + { + super.onOpen(); + + try { - // Read data - int fill = getEndPoint().fill(_buffer); - if (fill < 0) + parseHeader(); + if (_headerParsed && _buffer.remaining() >= _length) { - getEndPoint().shutdownOutput(); - return; + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 onOpen parsing fixed length packet part done, now upgrading"); + parseBodyAndUpgrade(); } - if (fill == 0) + else { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 onOpen parsing fixed length packet ran out of bytes, marking as fillInterested"); fillInterested(); - return; } } - next(); - } - catch (Throwable x) - { - LOG.warn("PROXY error for " + getEndPoint(), x); - close(); - } - } - - private void next() - { - if (LOG.isDebugEnabled()) - LOG.debug("PROXYv2 next {} from {} for {}", _next, BufferUtil.toHexSummary(_buffer), this); - - // Create the next protocol - ConnectionFactory connectionFactory = _connector.getConnectionFactory(_next); - if (connectionFactory == null) - { - LOG.info("Next protocol '{}' for {}", _next, getEndPoint()); - close(); - return; + catch (Exception x) + { + LOG.warn("Proxy v2 error for {}", getEndPoint(), x); + releaseAndClose(); + } } - // Do we need to wrap the endpoint? - EndPoint endPoint = getEndPoint(); - if (!_local) + @Override + public void onFillable() { try + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 onFillable header parsed? ", _headerParsed); + while (!_headerParsed) + { + // Read data + int fill = getEndPoint().fill(_buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 filled buffer with {} bytes", fill); + if (fill < 0) + { + _connector.getByteBufferPool().release(_buffer); + getEndPoint().shutdownOutput(); + return; + } + if (fill == 0) + { + fillInterested(); + return; + } + + parseHeader(); + } + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 onFillable header parsed, length = {}, buffer = {}", _length, BufferUtil.toDetailString(_buffer)); + + while (_buffer.remaining() < _length) + { + // Read data + int fill = getEndPoint().fill(_buffer); + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 filled buffer with {} bytes", fill); + if (fill < 0) + { + _connector.getByteBufferPool().release(_buffer); + getEndPoint().shutdownOutput(); + return; + } + if (fill == 0) + { + fillInterested(); + return; + } + } + + parseBodyAndUpgrade(); + } + catch (Throwable x) + { + LOG.warn("Proxy v2 error for " + getEndPoint(), x); + releaseAndClose(); + } + } + + @Override + public ByteBuffer onUpgradeFrom() + { + return _buffer; + } + + private void parseBodyAndUpgrade() throws IOException + { + // stop reading when bufferRemainingReserve bytes are remaining in the buffer + int nonProxyRemaining = _buffer.remaining() - _length; + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 parsing body, length = {}, buffer = {}", _length, BufferUtil.toHexSummary(_buffer)); + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 body {} from {} for {}", _next, BufferUtil.toHexSummary(_buffer), this); + + // Do we need to wrap the endpoint? + EndPoint endPoint = getEndPoint(); + if (!_local) { InetAddress src; InetAddress dst; @@ -532,15 +596,15 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory endPoint = proxyEndPoint; // Any additional info? - while (_buffer.hasRemaining()) + while (_buffer.remaining() > nonProxyRemaining) { int type = 0xff & _buffer.get(); - int length = _buffer.getShort(); + int length = _buffer.getChar(); byte[] value = new byte[length]; _buffer.get(value); if (LOG.isDebugEnabled()) - LOG.debug(String.format("T=%x L=%d V=%s for %s", type, length, TypeUtil.toHexString(value), this)); + LOG.debug(String.format("Proxy v2 T=%x L=%d V=%s for %s", type, length, TypeUtil.toHexString(value), this)); switch (type) { @@ -593,16 +657,94 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory } if (LOG.isDebugEnabled()) - LOG.debug("{} {}", getEndPoint(), proxyEndPoint.toString()); - } - catch (Exception e) - { - LOG.warn(e); + LOG.debug("Proxy v2 {} {}", getEndPoint(), proxyEndPoint.toString()); } + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 parsing dynamic packet part is now done, upgrading to {}", _nextProtocol); + upgradeToConnectionFactory(_next, _connector, endPoint); } - Connection newConnection = connectionFactory.newConnection(_connector, endPoint); - endPoint.upgrade(newConnection); + private void parseHeader() throws IOException + { + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 parsing fixed length packet part, buffer = {}", BufferUtil.toDetailString(_buffer)); + if (_buffer.remaining() < HEADER_LENGTH) + return; + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 header {} for {}", BufferUtil.toHexSummary(_buffer), this); + + // struct proxy_hdr_v2 { + // uint8_t sig[12]; /* hex 0D 0A 0D 0A 00 0D 0A 51 55 49 54 0A */ + // uint8_t ver_cmd; /* protocol version and command */ + // uint8_t fam; /* protocol family and address */ + // uint16_t len; /* number of following bytes part of the header */ + // }; + for (byte signatureByte : SIGNATURE) + { + if (_buffer.get() != signatureByte) + throw new IOException("Proxy v2 bad PROXY signature"); + } + + int versionAndCommand = 0xFF & _buffer.get(); + if ((versionAndCommand & 0xF0) != 0x20) + throw new IOException("Proxy v2 bad PROXY version"); + _local = (versionAndCommand & 0xF) == 0x00; + + int transportAndFamily = 0xFF & _buffer.get(); + switch (transportAndFamily >> 4) + { + case 0: + _family = Family.UNSPEC; + break; + case 1: + _family = Family.INET; + break; + case 2: + _family = Family.INET6; + break; + case 3: + _family = Family.UNIX; + break; + default: + throw new IOException("Proxy v2 bad PROXY family"); + } + + Transport transport; + switch (0xF & transportAndFamily) + { + case 0: + transport = Transport.UNSPEC; + break; + case 1: + transport = Transport.STREAM; + break; + case 2: + transport = Transport.DGRAM; + break; + default: + throw new IOException("Proxy v2 bad PROXY family"); + } + + _length = _buffer.getChar(); + + if (!_local && (_family == Family.UNSPEC || _family == Family.UNIX || transport != Transport.STREAM)) + throw new IOException(String.format("Proxy v2 unsupported PROXY mode 0x%x,0x%x", versionAndCommand, transportAndFamily)); + + if (_length > getMaxProxyHeader()) + throw new IOException(String.format("Proxy v2 Unsupported PROXY mode 0x%x,0x%x,0x%x", versionAndCommand, transportAndFamily, _length)); + + if (LOG.isDebugEnabled()) + LOG.debug("Proxy v2 fixed length packet part is now parsed"); + _headerParsed = true; + } + + private void releaseAndClose() + { + _connector.getByteBufferPool().release(_buffer); + close(); + } } } @@ -619,65 +761,6 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory _local = local; } - @Override - public boolean isOptimizedForDirectBuffers() - { - return _endp.isOptimizedForDirectBuffers(); - } - - @Override - public InetSocketAddress getLocalAddress() - { - return _local; - } - - @Override - public InetSocketAddress getRemoteAddress() - { - return _remote; - } - - @Override - public String toString() - { - return String.format("%s@%x[remote=%s,local=%s,endpoint=%s]", - getClass().getSimpleName(), - hashCode(), - _remote, - _local, - _endp); - } - - @Override - public boolean isOpen() - { - return _endp.isOpen(); - } - - @Override - public long getCreatedTimeStamp() - { - return _endp.getCreatedTimeStamp(); - } - - @Override - public void shutdownOutput() - { - _endp.shutdownOutput(); - } - - @Override - public boolean isOutputShutdown() - { - return _endp.isOutputShutdown(); - } - - @Override - public boolean isInputShutdown() - { - return _endp.isInputShutdown(); - } - @Override public void close() { @@ -690,30 +773,6 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory return _endp.fill(buffer); } - @Override - public boolean flush(ByteBuffer... buffer) throws IOException - { - return _endp.flush(buffer); - } - - @Override - public Object getTransport() - { - return _endp.getTransport(); - } - - @Override - public long getIdleTimeout() - { - return _endp.getIdleTimeout(); - } - - @Override - public void setIdleTimeout(long idleTimeout) - { - _endp.setIdleTimeout(idleTimeout); - } - @Override public void fillInterested(Callback callback) throws ReadPendingException { @@ -721,21 +780,9 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory } @Override - public boolean tryFillInterested(Callback callback) + public boolean flush(ByteBuffer... buffer) throws IOException { - return _endp.tryFillInterested(callback); - } - - @Override - public boolean isFillInterested() - { - return _endp.isFillInterested(); - } - - @Override - public void write(Callback callback, ByteBuffer... buffers) throws WritePendingException - { - _endp.write(callback, buffers); + return _endp.flush(buffer); } @Override @@ -751,9 +798,69 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory } @Override - public void onOpen() + public long getCreatedTimeStamp() { - _endp.onOpen(); + return _endp.getCreatedTimeStamp(); + } + + @Override + public long getIdleTimeout() + { + return _endp.getIdleTimeout(); + } + + @Override + public void setIdleTimeout(long idleTimeout) + { + _endp.setIdleTimeout(idleTimeout); + } + + @Override + public InetSocketAddress getLocalAddress() + { + return _local; + } + + @Override + public InetSocketAddress getRemoteAddress() + { + return _remote; + } + + @Override + public Object getTransport() + { + return _endp.getTransport(); + } + + @Override + public boolean isFillInterested() + { + return _endp.isFillInterested(); + } + + @Override + public boolean isInputShutdown() + { + return _endp.isInputShutdown(); + } + + @Override + public boolean isOpen() + { + return _endp.isOpen(); + } + + @Override + public boolean isOptimizedForDirectBuffers() + { + return _endp.isOptimizedForDirectBuffers(); + } + + @Override + public boolean isOutputShutdown() + { + return _endp.isOutputShutdown(); } @Override @@ -762,10 +869,45 @@ public class ProxyConnectionFactory extends AbstractConnectionFactory _endp.onClose(); } + @Override + public void onOpen() + { + _endp.onOpen(); + } + + @Override + public void shutdownOutput() + { + _endp.shutdownOutput(); + } + + @Override + public String toString() + { + return String.format("%s@%x[remote=%s,local=%s,endpoint=%s]", + getClass().getSimpleName(), + hashCode(), + _remote, + _local, + _endp); + } + + @Override + public boolean tryFillInterested(Callback callback) + { + return _endp.tryFillInterested(callback); + } + @Override public void upgrade(Connection newConnection) { _endp.upgrade(newConnection); } + + @Override + public void write(Callback callback, ByteBuffer... buffers) throws WritePendingException + { + _endp.write(callback, buffers); + } } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/SslConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/SslConnectionFactory.java index e3b2a905314..d3aae80c97d 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/SslConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/SslConnectionFactory.java @@ -18,6 +18,7 @@ package org.eclipse.jetty.server; +import java.nio.ByteBuffer; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; @@ -31,8 +32,12 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.ssl.SslContextFactory; -public class SslConnectionFactory extends AbstractConnectionFactory +public class SslConnectionFactory extends AbstractConnectionFactory implements ConnectionFactory.Detecting { + private static final int TLS_ALERT_FRAME_TYPE = 0x15; + private static final int TLS_HANDSHAKE_FRAME_TYPE = 0x16; + private static final int TLS_MAJOR_VERSION = 3; + private final SslContextFactory _sslContextFactory; private final String _nextProtocol; private boolean _directBuffersForEncryption = false; @@ -99,6 +104,17 @@ public class SslConnectionFactory extends AbstractConnectionFactory setInputBufferSize(session.getPacketBufferSize()); } + @Override + public Detection detect(ByteBuffer buffer) + { + if (buffer.remaining() < 2) + return Detection.NEED_MORE_BYTES; + int tlsFrameType = buffer.get(0) & 0xFF; + int tlsMajorVersion = buffer.get(1) & 0xFF; + boolean seemsSsl = (tlsFrameType == TLS_HANDSHAKE_FRAME_TYPE || tlsFrameType == TLS_ALERT_FRAME_TYPE) && tlsMajorVersion == TLS_MAJOR_VERSION; + return seemsSsl ? Detection.RECOGNIZED : Detection.NOT_RECOGNIZED; + } + @Override public Connection newConnection(Connector connector, EndPoint endPoint) { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java new file mode 100644 index 00000000000..2663338b279 --- /dev/null +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java @@ -0,0 +1,715 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.server; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.Socket; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.net.ssl.SSLSocketFactory; + +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.io.AbstractConnection; +import org.eclipse.jetty.io.Connection; +import org.eclipse.jetty.io.EndPoint; +import org.eclipse.jetty.toolchain.test.MavenTestingUtils; +import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.TypeUtil; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class DetectorConnectionTest +{ + private Server _server; + + private static String inputStreamToString(InputStream is) throws IOException + { + StringBuilder sb = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.US_ASCII)); + + while (true) + { + String line = reader.readLine(); + if (line == null) + { + // remove the last '\n' + if (sb.length() != 0) + sb.deleteCharAt(sb.length() - 1); + break; + } + sb.append(line).append('\n'); + } + + return sb.length() == 0 ? null : sb.toString(); + } + + private String getResponse(String request) throws Exception + { + return getResponse(request.getBytes(StandardCharsets.US_ASCII)); + } + + private String getResponse(byte[]... requests) throws Exception + { + try (Socket socket = new Socket(_server.getURI().getHost(), _server.getURI().getPort())) + { + for (byte[] request : requests) + { + socket.getOutputStream().write(request); + } + return inputStreamToString(socket.getInputStream()); + } + } + + private String getResponseOverSsl(String request) throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + sslContextFactory.start(); + + SSLSocketFactory socketFactory = sslContextFactory.getSslContext().getSocketFactory(); + try (Socket socket = socketFactory.createSocket(_server.getURI().getHost(), _server.getURI().getPort())) + { + socket.getOutputStream().write(request.getBytes(StandardCharsets.US_ASCII)); + return inputStreamToString(socket.getInputStream()); + } + finally + { + sslContextFactory.stop(); + } + } + + private void start(ConnectionFactory... connectionFactories) throws Exception + { + _server = new Server(); + _server.addConnector(new ServerConnector(_server, 1, 1, connectionFactories)); + _server.setHandler(new DumpHandler()); + _server.start(); + } + + @AfterEach + public void destroy() throws Exception + { + if (_server != null) + _server.stop(); + } + + @Test + public void testConnectionClosedDuringDetection() throws Exception + { + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, http); + + try (Socket socket = new Socket(_server.getURI().getHost(), _server.getURI().getPort())) + { + socket.getOutputStream().write("PR".getBytes(StandardCharsets.US_ASCII)); + Thread.sleep(100); // make sure the onFillable callback gets called + socket.getOutputStream().write("OX".getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().close(); + + assertThrows(SocketException.class, () -> socket.getInputStream().read()); + } + } + + @Test + public void testConnectionClosedDuringProxyV1Handling() throws Exception + { + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, http); + + try (Socket socket = new Socket(_server.getURI().getHost(), _server.getURI().getPort())) + { + socket.getOutputStream().write("PROXY".getBytes(StandardCharsets.US_ASCII)); + Thread.sleep(100); // make sure the onFillable callback gets called + socket.getOutputStream().write(" ".getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().close(); + + assertThrows(SocketException.class, () -> socket.getInputStream().read()); + } + } + + @Test + public void testConnectionClosedDuringProxyV2HandlingFixedLengthPart() throws Exception + { + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, http); + + try (Socket socket = new Socket(_server.getURI().getHost(), _server.getURI().getPort())) + { + socket.getOutputStream().write(TypeUtil.fromHexString("0D0A0D0A000D0A515549540A")); // proxy V2 Preamble + Thread.sleep(100); // make sure the onFillable callback gets called + socket.getOutputStream().write(TypeUtil.fromHexString("21")); // V2, PROXY + socket.getOutputStream().close(); + + assertThrows(SocketException.class, () -> socket.getInputStream().read()); + } + } + + @Test + public void testConnectionClosedDuringProxyV2HandlingDynamicLengthPart() throws Exception + { + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, http); + + try (Socket socket = new Socket(_server.getURI().getHost(), _server.getURI().getPort())) + { + socket.getOutputStream().write(TypeUtil.fromHexString( + // proxy V2 Preamble + "0D0A0D0A000D0A515549540A" + + // V2, PROXY + "21" + + // 0x1 : AF_INET 0x1 : STREAM. + "11" + + // Address length is 2*4 + 2*2 = 12 bytes. + // length of remaining header (4+4+2+2 = 12) + "000C" + )); + Thread.sleep(100); // make sure the onFillable callback gets called + socket.getOutputStream().write(TypeUtil.fromHexString( + // uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; + "C0A80001" // 8080 + )); + socket.getOutputStream().close(); + + assertThrows(SocketException.class, () -> socket.getInputStream().read()); + } + } + + @Test + public void testDetectingSslProxyToHttpNoSslWithProxy() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl, proxy); + + start(detector, http); + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + assertThat(response, Matchers.containsString("pathInfo=/path")); + assertThat(response, Matchers.containsString("local=5.6.7.8:222")); + assertThat(response, Matchers.containsString("remote=1.2.3.4:111")); + } + + @Test + public void testDetectingSslProxyToHttpWithSslNoProxy() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl, proxy); + + start(detector, http); + + String request = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponseOverSsl(request); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + } + + @Test + public void testDetectingSslProxyToHttpWithSslWithProxy() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl, proxy); + + start(detector, http); + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponseOverSsl(request); + + // SSL matched, so the upgrade was made to HTTP which does not understand the proxy request + assertThat(response, Matchers.containsString("HTTP/1.1 400")); + } + + @Test + public void testDetectionUnsuccessfulUpgradesToNextProtocol() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl, proxy); + + start(detector, http); + + String request = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + } + + @Test + void testDetectorToNextDetector() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory proxyDetector = new DetectorConnectionFactory(proxy); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, proxyDetector.getProtocol()); + DetectorConnectionFactory sslDetector = new DetectorConnectionFactory(ssl); + + start(sslDetector, proxyDetector, http); + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponseOverSsl(request); + + // SSL matched, so the upgrade was made to proxy which itself upgraded to HTTP + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + assertThat(response, Matchers.containsString("pathInfo=/path")); + assertThat(response, Matchers.containsString("local=5.6.7.8:222")); + assertThat(response, Matchers.containsString("remote=1.2.3.4:111")); + } + + @Test + void testDetectorWithDetectionUnsuccessful() throws Exception + { + AtomicBoolean detectionSuccessful = new AtomicBoolean(true); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy) + { + @Override + protected void nextProtocol(Connector connector, EndPoint endPoint, ByteBuffer buffer) + { + if (!detectionSuccessful.compareAndSet(true, false)) + throw new AssertionError("DetectionUnsuccessful callback should only have been called once"); + + // omitting this will leak the buffer + connector.getByteBufferPool().release(buffer); + + Callback.Completable completable = new Callback.Completable(); + endPoint.write(completable, ByteBuffer.wrap("No upgrade for you".getBytes(StandardCharsets.US_ASCII))); + completable.whenComplete((r, x) -> endPoint.close()); + } + }; + HttpConnectionFactory http = new HttpConnectionFactory(); + + start(detector, http); + + String request = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + assertEquals("No upgrade for you", response); + assertFalse(detectionSuccessful.get()); + } + + @Test + void testDetectorWithProxyThatHasNoNextProto() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl, proxy); + + start(detector, http); + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + // ProxyConnectionFactory has no next protocol -> it cannot upgrade + assertThat(response, Matchers.nullValue()); + } + + @Test + void testOptionalSsl() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConnectionFactory http = new HttpConnectionFactory(); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl); + + start(detector, http); + + String request = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String clearTextResponse = getResponse(request); + String sslResponse = getResponseOverSsl(request); + + // both clear text and SSL can be responded to just fine + assertThat(clearTextResponse, Matchers.containsString("HTTP/1.1 200")); + assertThat(sslResponse, Matchers.containsString("HTTP/1.1 200")); + } + + @Test + void testDetectorThatHasNoConfiguredNextProto() throws Exception + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl); + + start(detector); + + String request = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + assertThat(response, Matchers.nullValue()); + } + + @Test + void testDetectorWithNextProtocolThatDoesNotExist() throws Exception + { + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory("does-not-exist"); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, http); + + String proxyReq = + // proxy V2 Preamble + "0D0A0D0A000D0A515549540A" + + // V2, PROXY + "21" + + // 0x1 : AF_INET 0x1 : STREAM. + "11" + + // Address length is 2*4 + 2*2 = 12 bytes. + // length of remaining header (4+4+2+2 = 12) + "000C" + + // uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; + "C0A80001" + // 192.168.0.1 + "7f000001" + // 127.0.0.1 + "3039" + // 12345 + "1F90"; // 8080 + + String httpReq = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(TypeUtil.fromHexString(proxyReq), httpReq.getBytes(StandardCharsets.US_ASCII)); + + assertThat(response, Matchers.nullValue()); + } + + @Test + void testDetectingWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception + { + ConnectionFactory.Detecting noUpgradeTo = new ConnectionFactory.Detecting() + { + @Override + public Detection detect(ByteBuffer buffer) + { + return Detection.RECOGNIZED; + } + + @Override + public String getProtocol() + { + return "noUpgradeTo"; + } + + @Override + public List getProtocols() + { + return Collections.singletonList(getProtocol()); + } + + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) + { + return new AbstractConnection(null, connector.getExecutor()) + { + @Override + public void onFillable() + { + } + }; + } + }; + + HttpConnectionFactory http = new HttpConnectionFactory(); + DetectorConnectionFactory detector = new DetectorConnectionFactory(noUpgradeTo); + + start(detector, http); + + String proxyReq = + // proxy V2 Preamble + "0D0A0D0A000D0A515549540A" + + // V2, PROXY + "21" + + // 0x1 : AF_INET 0x1 : STREAM. + "11" + + // Address length is 2*4 + 2*2 = 12 bytes. + // length of remaining header (4+4+2+2 = 12) + "000C" + + // uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; + "C0A80001" + // 192.168.0.1 + "7f000001" + // 127.0.0.1 + "3039" + // 12345 + "1F90"; // 8080 + + String httpReq = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(TypeUtil.fromHexString(proxyReq), httpReq.getBytes(StandardCharsets.US_ASCII)); + + assertThat(response, Matchers.nullValue()); + } + + @Test + void testDetectorWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception + { + ConnectionFactory noUpgradeTo = new ConnectionFactory() + { + @Override + public String getProtocol() + { + return "noUpgradeTo"; + } + + @Override + public List getProtocols() + { + return Collections.singletonList(getProtocol()); + } + + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) + { + return new AbstractConnection(null, connector.getExecutor()) + { + @Override + public void onFillable() + { + } + }; + } + }; + + HttpConnectionFactory http = new HttpConnectionFactory(); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); + DetectorConnectionFactory detector = new DetectorConnectionFactory(proxy); + + start(detector, noUpgradeTo); + + String request = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = getResponse(request); + + assertThat(response, Matchers.nullValue()); + } + + @Test + void testGeneratedProtocolNames() + { + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); + + assertEquals("SSL|proxy", new DetectorConnectionFactory(ssl, proxy).getProtocol()); + assertEquals("proxy|SSL", new DetectorConnectionFactory(proxy, ssl).getProtocol()); + } + + @Test + void testDetectorWithNoDetectingFails() + { + assertThrows(IllegalArgumentException.class, DetectorConnectionFactory::new); + } + + @Test + void testExerciseDetectorNotEnoughBytes() throws Exception + { + ConnectionFactory.Detecting detectingNeverRecognizes = new ConnectionFactory.Detecting() + { + @Override + public Detection detect(ByteBuffer buffer) + { + return Detection.NOT_RECOGNIZED; + } + + @Override + public String getProtocol() + { + return "nevergood"; + } + + @Override + public List getProtocols() + { + throw new AssertionError(); + } + + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) + { + throw new AssertionError(); + } + }; + + ConnectionFactory.Detecting detectingAlwaysNeedMoreBytes = new ConnectionFactory.Detecting() + { + @Override + public Detection detect(ByteBuffer buffer) + { + return Detection.NEED_MORE_BYTES; + } + + @Override + public String getProtocol() + { + return "neverenough"; + } + + @Override + public List getProtocols() + { + throw new AssertionError(); + } + + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) + { + throw new AssertionError(); + } + }; + + DetectorConnectionFactory detector = new DetectorConnectionFactory(detectingNeverRecognizes, detectingAlwaysNeedMoreBytes); + HttpConnectionFactory http = new HttpConnectionFactory(); + + start(detector, http); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 32768; i++) + { + sb.append("AAAA"); + } + String request = sb.toString(); + String response = getResponse(request); + + assertThat(response, Matchers.nullValue()); + } +} diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java index 35c81935106..699081acff1 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java @@ -38,6 +38,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class OptionalSslConnectionTest { @@ -60,7 +61,7 @@ public class OptionalSslConnectionTest HttpConnectionFactory http = new HttpConnectionFactory(httpConfig); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); OptionalSslConnectionFactory sslOrOther = configFn.apply(ssl); - connector = new ServerConnector(server, 1, 1, sslOrOther, ssl, http); + connector = new ServerConnector(server, 1, 1, sslOrOther, http); server.addConnector(connector); server.setHandler(handler); @@ -204,6 +205,47 @@ public class OptionalSslConnectionTest } } + @Test + void testNextProtocolIsNotNullButNotConfiguredEither() throws Exception + { + QueuedThreadPool serverThreads = new QueuedThreadPool(); + serverThreads.setName("server"); + server = new Server(serverThreads); + + String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + SslContextFactory sslContextFactory = new SslContextFactory.Server(); + sslContextFactory.setKeyStorePath(keystore); + sslContextFactory.setKeyStorePassword("storepwd"); + sslContextFactory.setKeyManagerPassword("keypwd"); + + HttpConfiguration httpConfig = new HttpConfiguration(); + HttpConnectionFactory http = new HttpConnectionFactory(httpConfig); + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); + OptionalSslConnectionFactory optSsl = new OptionalSslConnectionFactory(ssl, "no-such-protocol"); + connector = new ServerConnector(server, 1, 1, optSsl, http); + server.addConnector(connector); + server.setHandler(new EmptyServerHandler()); + server.start(); + + try (Socket socket = new Socket(server.getURI().getHost(), server.getURI().getPort())) + { + OutputStream sslOutput = socket.getOutputStream(); + String request = + "GET / HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "\r\n"; + byte[] requestBytes = request.getBytes(StandardCharsets.US_ASCII); + + sslOutput.write(requestBytes); + sslOutput.flush(); + + socket.setSoTimeout(5000); + InputStream sslInput = socket.getInputStream(); + HttpTester.Response response = HttpTester.parseResponse(sslInput); + assertNull(response); + } + } + private static class EmptyServerHandler extends AbstractHandler { @Override diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java index 2075a197205..9f709e2b08a 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java @@ -18,75 +18,94 @@ package org.eclipse.jetty.server; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.handler.ErrorHandler; import org.eclipse.jetty.toolchain.test.Net; +import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNull; public class ProxyConnectionTest { - private Server _server; - private LocalConnector _connector; - - @BeforeEach - public void init() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + public void testBadCRLF(RequestProcessor p) throws Exception { - _server = new Server(); - - HttpConnectionFactory http = new HttpConnectionFactory(); - http.getHttpConfiguration().setRequestHeaderSize(1024); - http.getHttpConfiguration().setResponseHeaderSize(1024); - - ProxyConnectionFactory proxy = new ProxyConnectionFactory(); - - _connector = new LocalConnector(_server, null, null, null, 1, proxy, http); - _connector.setIdleTimeout(1000); - _server.addConnector(_connector); - _server.setHandler(new DumpHandler()); - ErrorHandler eh = new ErrorHandler(); - eh.setServer(_server); - _server.addBean(eh); - _server.start(); - } - - @AfterEach - public void destroy() throws Exception - { - _server.stop(); - _server.join(); - } - - @Test - public void testSimple() throws Exception - { - String response = _connector.getResponse("PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r \n" + "GET /path HTTP/1.1\n" + "Host: server:80\n" + "Connection: close\n" + - "\n"); - - assertThat(response, Matchers.containsString("HTTP/1.1 200")); - assertThat(response, Matchers.containsString("pathInfo=/path")); - assertThat(response, Matchers.containsString("local=5.6.7.8:222")); - assertThat(response, Matchers.containsString("remote=1.2.3.4:111")); + "\n"; + String response = p.sendRequestWaitingForResponse(request); + assertNull(response); } - @Test - public void testIPv6() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + public void testBadChar(RequestProcessor p) throws Exception + { + String request = "PROXY\tTCP 1.2.3.4 5.6.7.8 111 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = p.sendRequestWaitingForResponse(request); + assertNull(response); + } + + @ParameterizedTest + @MethodSource("requestProcessors") + public void testBadPort(RequestProcessor p) throws Exception + { + try (StacklessLogging stackless = new StacklessLogging(ProxyConnectionFactory.class)) + { + String request = "PROXY TCP 1.2.3.4 5.6.7.8 9999999999999 222\r\n" + + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = p.sendRequestWaitingForResponse(request); + assertNull(response); + } + } + + @ParameterizedTest + @MethodSource("requestProcessors") + public void testHttp(RequestProcessor p) throws Exception + { + String request = + "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + String response = p.sendRequestWaitingForResponse(request); + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + } + + @ParameterizedTest + @MethodSource("requestProcessors") + public void testIPv6(RequestProcessor p) throws Exception { Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable()); - String response = _connector.getResponse("PROXY TCP6 eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n" + + String request = "PROXY TCP6 eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n" + "GET /path HTTP/1.1\n" + "Host: server:80\n" + "Connection: close\n" + - "\n"); + "\n"; + + String response = p.sendRequestWaitingForResponse(request); assertThat(response, Matchers.containsString("HTTP/1.1 200")); assertThat(response, Matchers.containsString("pathInfo=/path")); @@ -94,83 +113,272 @@ public class ProxyConnectionTest assertThat(response, Matchers.containsString("local=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:65535")); } - @Test - public void testTooLong() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + public void testIPv6V2(RequestProcessor p) throws Exception { - String response = _connector.getResponse("PROXY TOOLONG!!! eeee:eeee:eeee:eeee:0000:0000:0000:0000 ffff:ffff:ffff:ffff:0000:0000:0000:0000 65535 65535\r\n" + + Assumptions.assumeTrue(Net.isIpv6InterfaceAvailable()); + + String proxy = + // Preamble + "0D0A0D0A000D0A515549540A" + + + // V2, PROXY + "21" + + + // 0x1 : AF_INET6 0x1 : STREAM. + "21" + + + // Address length is 2*16 + 2*2 = 36 bytes. + // length of remaining header (16+16+2+2 = 36) + "0024" + + + // uint8_t src_addr[16]; uint8_t dst_addr[16]; uint16_t src_port; uint16_t dst_port; + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + // ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff + "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + // eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee + "3039" + // 12345 + "1F90"; // 8080 + String http = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + + String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII)); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + assertThat(response, Matchers.containsString("pathInfo=/path")); + assertThat(response, Matchers.containsString("local=eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee:8080")); + assertThat(response, Matchers.containsString("remote=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:12345")); + } + + @ParameterizedTest + @MethodSource("requestProcessors") + public void testMissingField(RequestProcessor p) throws Exception + { + String request = "PROXY TCP 1.2.3.4 5.6.7.8 222\r\n" + "GET /path HTTP/1.1\n" + "Host: server:80\n" + "Connection: close\n" + - "\n"); - + "\n"; + String response = p.sendRequestWaitingForResponse(request); assertNull(response); } - @Test - public void testNotComplete() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + public void testNotComplete(RequestProcessor p) throws Exception { - _connector.setIdleTimeout(100); - String response = _connector.getResponse("PROXY TIMEOUT"); + String response = p.customize(connector -> connector.setIdleTimeout(100)).sendRequestWaitingForResponse("PROXY TIMEOUT"); assertNull(response); } - @Test - public void testBadChar() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + public void testTooLong(RequestProcessor p) throws Exception { - String response = _connector.getResponse("PROXY\tTCP 1.2.3.4 5.6.7.8 111 222\r\n" + + String request = "PROXY TOOLONG!!! eeee:eeee:eeee:eeee:0000:0000:0000:0000 ffff:ffff:ffff:ffff:0000:0000:0000:0000 65535 65535\r\n" + "GET /path HTTP/1.1\n" + "Host: server:80\n" + "Connection: close\n" + - "\n"); + "\n"; + + String response = p.sendRequestWaitingForResponse(request); + assertNull(response); } - @Test - public void testBadCRLF() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + void testSimple(RequestProcessor p) throws Exception { - String response = _connector.getResponse("PROXY TCP 1.2.3.4 5.6.7.8 111 222\r \n" + + String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + "GET /path HTTP/1.1\n" + "Host: server:80\n" + "Connection: close\n" + - "\n"); - assertNull(response); + "\n"; + + String response = p.sendRequestWaitingForResponse(request); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + assertThat(response, Matchers.containsString("pathInfo=/path")); + assertThat(response, Matchers.containsString("local=5.6.7.8:222")); + assertThat(response, Matchers.containsString("remote=1.2.3.4:111")); } - @Test - public void testBadPort() throws Exception + @ParameterizedTest + @MethodSource("requestProcessors") + void testSimpleV2(RequestProcessor p) throws Exception { - try (StacklessLogging stackless = new StacklessLogging(ProxyConnectionFactory.class)) + String proxy = + // Preamble + "0D0A0D0A000D0A515549540A" + + + // V2, PROXY + "21" + + + // 0x1 : AF_INET 0x1 : STREAM. + "11" + + + // Address length is 2*4 + 2*2 = 12 bytes. + // length of remaining header (4+4+2+2 = 12) + "000C" + + + // uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; + "C0A80001" + // 192.168.0.1 + "7f000001" + // 127.0.0.1 + "3039" + // 12345 + "1F90"; // 8080 + String http = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + + String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII)); + + assertThat(response, Matchers.containsString("HTTP/1.1 200")); + assertThat(response, Matchers.containsString("pathInfo=/path")); + assertThat(response, Matchers.containsString("local=127.0.0.1:8080")); + assertThat(response, Matchers.containsString("remote=192.168.0.1:12345")); + } + + @ParameterizedTest + @MethodSource("requestProcessors") + void testMaxHeaderLengthV2(RequestProcessor p) throws Exception + { + p.customize((connector) -> { - String response = _connector.getResponse("PROXY TCP 1.2.3.4 5.6.7.8 9999999999999 222\r\n" + - "GET /path HTTP/1.1\n" + - "Host: server:80\n" + - "Connection: close\n" + - "\n"); - assertNull(response); + ProxyConnectionFactory factory = (ProxyConnectionFactory)connector.getConnectionFactory("proxy"); + factory.setMaxProxyHeader(11); // just one byte short + }); + String proxy = + // Preamble + "0D0A0D0A000D0A515549540A" + + + // V2, PROXY + "21" + + + // 0x1 : AF_INET 0x1 : STREAM. + "11" + + + // Address length is 2*4 + 2*2 = 12 bytes. + // length of remaining header (4+4+2+2 = 12) + "000C" + + + // uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; + "C0A80001" + + "7f000001" + + "3039" + + "1F90"; + String http = "GET /path HTTP/1.1\n" + + "Host: server:80\n" + + "Connection: close\n" + + "\n"; + + String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII)); + + assertThat(response, Matchers.is(Matchers.nullValue())); + } + + abstract static class RequestProcessor + { + protected LocalConnector _connector; + private Server _server; + + public RequestProcessor() + { + _server = new Server(); + HttpConnectionFactory http = new HttpConnectionFactory(); + http.getHttpConfiguration().setRequestHeaderSize(1024); + http.getHttpConfiguration().setResponseHeaderSize(1024); + ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); + + _connector = new LocalConnector(_server, null, null, null, 1, proxy, http); + _connector.setIdleTimeout(1000); + _server.addConnector(_connector); + _server.setHandler(new DumpHandler()); + ErrorHandler eh = new ErrorHandler(); + eh.setServer(_server); + _server.addBean(eh); + } + + public RequestProcessor customize(Consumer consumer) + { + consumer.accept(_connector); + return this; + } + + public final String sendRequestWaitingForResponse(String request) throws Exception + { + return sendRequestWaitingForResponse(request.getBytes(StandardCharsets.US_ASCII)); + } + + public final String sendRequestWaitingForResponse(byte[]... requests) throws Exception + { + try + { + _server.start(); + return process(requests); + } + finally + { + destroy(); + } + } + + protected abstract String process(byte[]... requests) throws Exception; + + private void destroy() throws Exception + { + _server.stop(); + _server.join(); } } - @Test - public void testMissingField() throws Exception + static Stream requestProcessors() { - String response = _connector.getResponse("PROXY TCP 1.2.3.4 5.6.7.8 222\r\n" + - "GET /path HTTP/1.1\n" + - "Host: server:80\n" + - "Connection: close\n" + - "\n"); - assertNull(response); + return Stream.of( + Arguments.of(new RequestProcessor() + { + @Override + public String process(byte[]... requests) throws Exception + { + LocalConnector.LocalEndPoint endPoint = _connector.connect(); + for (byte[] request : requests) + { + endPoint.addInput(ByteBuffer.wrap(request)); + } + return endPoint.getResponse(); + } + + @Override + public String toString() + { + return "All bytes at once"; + } + }), + Arguments.of(new RequestProcessor() + { + @Override + public String process(byte[]... requests) throws Exception + { + LocalConnector.LocalEndPoint endPoint = _connector.connect(); + for (byte[] request : requests) + { + for (byte b : request) + { + endPoint.addInput(ByteBuffer.wrap(new byte[]{b})); + } + } + return endPoint.getResponse(); + } + + @Override + public String toString() + { + return "Byte by byte"; + } + }) + ); } - @Test - public void testHTTP() throws Exception - { - String response = _connector.getResponse( - "GET /path HTTP/1.1\n" + - "Host: server:80\n" + - "Connection: close\n" + - "\n"); - assertNull(response); - } } - - From 37edc016d2d3f4c006b5f5835b75fa019080a421 Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Tue, 4 Feb 2020 09:21:41 +0100 Subject: [PATCH 02/27] improve debug logs Signed-off-by: Ludovic Orban --- .../org/eclipse/jetty/server/DetectorConnectionFactory.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java index 0332329ab9b..690563e5e2d 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java @@ -79,7 +79,7 @@ public class DetectorConnectionFactory extends AbstractConnectionFactory impleme public Detecting.Detection detect(ByteBuffer buffer) { if (LOG.isDebugEnabled()) - LOG.debug("Attempting detection from buffer {} using {}", buffer, _detectingConnectionFactories); + LOG.debug("Detector {} detecting from buffer {} using {}", getProtocol(), BufferUtil.toHexString(buffer), _detectingConnectionFactories); boolean needMoreBytes = true; for (Detecting detectingConnectionFactory : _detectingConnectionFactories) { @@ -87,13 +87,13 @@ public class DetectorConnectionFactory extends AbstractConnectionFactory impleme if (detection == Detecting.Detection.RECOGNIZED) { if (LOG.isDebugEnabled()) - LOG.debug("Detection recognized bytes from buffer {} using {}", buffer, _detectingConnectionFactories); + LOG.debug("Detector {} recognized bytes using {}", getProtocol(), detection); return Detecting.Detection.RECOGNIZED; } needMoreBytes &= detection == Detection.NEED_MORE_BYTES; } if (LOG.isDebugEnabled()) - LOG.debug("Detection {} from buffer {} using {}", (needMoreBytes ? "requires more bytes" : "not recognized"), buffer, _detectingConnectionFactories); + LOG.debug("Detector {} {}", getProtocol(), (needMoreBytes ? "requires more bytes" : "failed to recognize bytes")); return needMoreBytes ? Detection.NEED_MORE_BYTES : Detection.NOT_RECOGNIZED; } From 58b1db610c96befe7c0d3eca7c57a07eb7be7cc7 Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Tue, 4 Feb 2020 10:49:27 +0100 Subject: [PATCH 03/27] detectAndUpgrade() shortcut on empty buffer Signed-off-by: Ludovic Orban --- .../eclipse/jetty/server/DetectorConnectionFactory.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java index 690563e5e2d..3f280a674d4 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java @@ -218,6 +218,13 @@ public class DetectorConnectionFactory extends AbstractConnectionFactory impleme */ private boolean detectAndUpgrade() { + if (BufferUtil.isEmpty(_buffer)) + { + if (LOG.isDebugEnabled()) + LOG.debug("Detector {} skipping detection on an empty buffer", getProtocol()); + return false; + } + if (LOG.isDebugEnabled()) LOG.debug("Detector {} performing detection with {} bytes", getProtocol(), _buffer.remaining()); boolean notRecognized = true; From 5df1ad9b6693b86a84aca82f3fc76151bd302ffa Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Tue, 4 Feb 2020 10:50:24 +0100 Subject: [PATCH 04/27] change the format of detector's generated protocol name Signed-off-by: Ludovic Orban --- .../jetty/server/AbstractConnectionFactory.java | 7 ++++++- .../org/eclipse/jetty/server/AbstractConnector.java | 5 +++-- .../jetty/server/DetectorConnectionFactory.java | 2 +- .../jetty/server/ProxyConnectionFactory.java | 13 +++++++------ .../jetty/server/DetectorConnectionTest.java | 4 ++-- .../eclipse/jetty/server/ProxyConnectionTest.java | 2 +- 6 files changed, 20 insertions(+), 13 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java index ac7079eea89..2bb76ccbd5c 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnectionFactory.java @@ -89,12 +89,17 @@ public abstract class AbstractConnectionFactory extends ContainerLifeCycle imple } protected String findNextProtocol(Connector connector) + { + return findNextProtocol(connector, getProtocol()); + } + + protected static String findNextProtocol(Connector connector, String currentProtocol) { String nextProtocol = null; for (Iterator it = connector.getProtocols().iterator(); it.hasNext(); ) { String protocol = it.next(); - if (getProtocol().equalsIgnoreCase(protocol)) + if (currentProtocol.equalsIgnoreCase(protocol)) { nextProtocol = it.hasNext() ? it.next() : null; break; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java index ab4d153f65a..30991980829 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java @@ -36,6 +36,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; +import java.util.stream.Collectors; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.io.ByteBufferPool; @@ -776,9 +777,9 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co @Override public String toString() { - return String.format("%s@%x{%s,%s}", + return String.format("%s@%x{%s, %s}", _name == null ? getClass().getSimpleName() : _name, hashCode(), - getDefaultProtocol(), getProtocols()); + getDefaultProtocol(), getProtocols().stream().collect(Collectors.joining(", ", "(", ")"))); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java index 3f280a674d4..5b28db46111 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/DetectorConnectionFactory.java @@ -64,7 +64,7 @@ public class DetectorConnectionFactory extends AbstractConnectionFactory impleme // remove protocol duplicates while keeping their ordering -> use LinkedHashSet LinkedHashSet protocols = Arrays.stream(detectingConnectionFactories).map(ConnectionFactory::getProtocol).collect(Collectors.toCollection(LinkedHashSet::new)); - String protocol = String.join("|", protocols); + String protocol = protocols.stream().collect(Collectors.joining("|", "[", "]")); if (LOG.isDebugEnabled()) LOG.debug("Detector generated protocol name : {}", protocol); return protocol; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java index d895e120055..2f4b699307c 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java @@ -60,15 +60,16 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory super(new ProxyV1ConnectionFactory(nextProtocol), new ProxyV2ConnectionFactory(nextProtocol)); } - private static ConnectionFactory findNextConnectionFactory(String nextProtocol, Connector connector, AbstractConnectionFactory currentConnectionFactory, EndPoint endp) + private static ConnectionFactory findNextConnectionFactory(String nextProtocol, Connector connector, String currentProtocol, EndPoint endp) { + currentProtocol = "[" + currentProtocol + "]"; if (LOG.isDebugEnabled()) - LOG.debug("finding next connection factory for protocol {}", nextProtocol); + LOG.debug("finding connection factory following {} for protocol {}", currentProtocol, nextProtocol); String nextProtocolToFind = nextProtocol; if (nextProtocol == null) - nextProtocolToFind = currentConnectionFactory.findNextProtocol(connector); + nextProtocolToFind = AbstractConnectionFactory.findNextProtocol(connector, currentProtocol); if (nextProtocolToFind == null) - throw new IllegalStateException("Cannot find protocol following '" + currentConnectionFactory.getProtocol() + "' in connector's protocol list " + connector.getProtocols() + " for " + endp); + throw new IllegalStateException("Cannot find protocol following '" + currentProtocol + "' in connector's protocol list " + connector.getProtocols() + " for " + endp); ConnectionFactory connectionFactory = connector.getConnectionFactory(nextProtocolToFind); if (connectionFactory == null) throw new IllegalStateException("Cannot find protocol '" + nextProtocol + "' in connector's protocol list " + connector.getProtocols() + " for " + endp); @@ -133,7 +134,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory @Override public Connection newConnection(Connector connector, EndPoint endp) { - ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, this, endp); + ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, getProtocol(), endp); return configure(new ProxyProtocolV1Connection(endp, connector, nextConnectionFactory), connector, endp); } @@ -414,7 +415,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory @Override public Connection newConnection(Connector connector, EndPoint endp) { - ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, this, endp); + ConnectionFactory nextConnectionFactory = findNextConnectionFactory(_nextProtocol, connector, getProtocol(), endp); return configure(new ProxyProtocolV2Connection(endp, connector, nextConnectionFactory), connector, endp); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java index 2663338b279..6f99f24264b 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java @@ -630,8 +630,8 @@ public class DetectorConnectionTest ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); - assertEquals("SSL|proxy", new DetectorConnectionFactory(ssl, proxy).getProtocol()); - assertEquals("proxy|SSL", new DetectorConnectionFactory(proxy, ssl).getProtocol()); + assertEquals("[SSL|[proxy]]", new DetectorConnectionFactory(ssl, proxy).getProtocol()); + assertEquals("[[proxy]|SSL]", new DetectorConnectionFactory(proxy, ssl).getProtocol()); } @Test diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java index 9f709e2b08a..9aa38e3554d 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java @@ -247,7 +247,7 @@ public class ProxyConnectionTest { p.customize((connector) -> { - ProxyConnectionFactory factory = (ProxyConnectionFactory)connector.getConnectionFactory("proxy"); + ProxyConnectionFactory factory = (ProxyConnectionFactory)connector.getConnectionFactory("[proxy]"); factory.setMaxProxyHeader(11); // just one byte short }); String proxy = From 1b59e422940edfd194a273fd0c3740b84c78660b Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Wed, 5 Feb 2020 10:29:41 +0100 Subject: [PATCH 05/27] Issue #4541 Large response header Fix #4541 by initially allocated a header buffer of `min(_config.getResponseHeaderSize(), _config.getOutputBufferSize())` Only allocate a buffer of `getResponseHeaderSize` if an overflow results. This should have no effect on the majority of responses where `getOutputBufferSize` is greater than `getResponseHeaderSize` other than the cost of a min operation. Signed-off-by: Greg Wilkins --- .../org/eclipse/jetty/http/HttpGenerator.java | 3 +- .../eclipse/jetty/server/HttpConnection.java | 18 +++++++- .../jetty/server/HttpConnectionTest.java | 43 +++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java index 84e50df364c..20b73f39fb8 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java @@ -445,7 +445,8 @@ public class HttpGenerator } catch (BufferOverflowException e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large", e); + LOG.ignore(e); + return Result.NEED_HEADER; } catch (Exception e) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java index 55a8dd1e068..15c357703f3 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java @@ -25,6 +25,7 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.LongAdder; +import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpCompliance; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpGenerator; @@ -47,6 +48,8 @@ import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +import static org.eclipse.jetty.http.HttpStatus.INTERNAL_SERVER_ERROR_500; + /** *

A {@link Connection} that handles the HTTP protocol.

*/ @@ -754,8 +757,19 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http case NEED_HEADER: { - _header = _bufferPool.acquire(_config.getResponseHeaderSize(), HEADER_BUFFER_DIRECT); - + int size; + if (_header == null) + { + size = Math.min(_config.getResponseHeaderSize(), _config.getOutputBufferSize()); + } + else + { + if (_header.capacity() >= _config.getResponseHeaderSize()) + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large"); + size = _config.getResponseHeaderSize(); + _bufferPool.release(_header); + } + _header = _bufferPool.acquire(size, HEADER_BUFFER_DIRECT); continue; } case NEED_CHUNK: diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpConnectionTest.java index 3f517d3ee5d..322823388d1 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpConnectionTest.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringReader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -1258,6 +1259,48 @@ public class HttpConnectionTest } } + @Test + public void testAllowedLargeResponse() throws Exception + { + connector.getBean(HttpConnectionFactory.class).getHttpConfiguration().setResponseHeaderSize(16 * 1024); + connector.getBean(HttpConnectionFactory.class).getHttpConfiguration().setOutputBufferSize(8 * 1024); + + byte[] bytes = new byte[12 * 1024]; + Arrays.fill(bytes, (byte)'X'); + final String longstr = "thisisastringthatshouldreachover12kbytes-" + new String(bytes, StandardCharsets.ISO_8859_1) + "_Z_"; + final CountDownLatch checkError = new CountDownLatch(1); + server.stop(); + server.setHandler(new AbstractHandler() + { + @SuppressWarnings("unused") + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + { + baseRequest.setHandled(true); + response.setHeader(HttpHeader.CONTENT_TYPE.toString(), MimeTypes.Type.TEXT_HTML.toString()); + response.setHeader("LongStr", longstr); + PrintWriter writer = response.getWriter(); + writer.write("

FOO

"); + writer.flush(); + if (writer.checkError()) + checkError.countDown(); + response.flushBuffer(); + } + }); + server.start(); + + String response = null; + response = connector.getResponse("GET / HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "\r\n" + ); + + checkContains(response, 0, "HTTP/1.1 200"); + checkContains(response, 0, "LongStr: thisisastringthatshouldreachover12kbytes"); + checkContains(response, 0, "XXX_Z_"); + assertThat(checkError.getCount(), is(1L)); + } + @Test public void testAsterisk() throws Exception { From 386d9348ca3d0f95a9456dcaa92782bc2d1e73ec Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Thu, 6 Feb 2020 10:06:33 +0100 Subject: [PATCH 06/27] Use contants for CR and LF fields index Signed-off-by: Ludovic Orban --- .../jetty/server/ProxyConnectionFactory.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java index 2f4b699307c..6cb0f7f9571 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ProxyConnectionFactory.java @@ -143,6 +143,8 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory // 0 1 2 3 4 5 6 // 98765432109876543210987654321 // PROXY P R.R.R.R L.L.L.L R Lrn + private static final int CR_INDEX = 6; + private static final int LF_INDEX = 7; private final Connector _connector; private final ConnectionFactory _next; @@ -167,7 +169,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory LOG.debug("Proxy v1 onFillable current index = ", _index); try { - while (_index < 7) + while (_index < LF_INDEX) { // Read data int fill = getEndPoint().fill(_buffer); @@ -207,7 +209,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory try { - while (_index < 7) + while (_index < LF_INDEX) { if (!parse()) { @@ -239,7 +241,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory public void onUpgradeTo(ByteBuffer prefilled) { if (LOG.isDebugEnabled()) - LOG.debug("Proxy v1 copying prefilled buffer {}", prefilled); + LOG.debug("Proxy v1 copying prefilled buffer {}", BufferUtil.toDetailString(prefilled)); if (BufferUtil.hasContent(prefilled)) BufferUtil.append(_buffer, prefilled); } @@ -257,14 +259,14 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory while (_buffer.hasRemaining()) { byte b = _buffer.get(); - if (_index < 6) + if (_index < CR_INDEX) { if (b == ' ' || b == '\r') { _fields[_index++] = _builder.toString(); _builder.setLength(0); if (b == '\r') - _index = 6; + _index = CR_INDEX; } else if (b < ' ') { @@ -279,7 +281,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory { if (b == '\n') { - _index = 7; + _index = LF_INDEX; if (LOG.isDebugEnabled()) LOG.debug("Proxy v1 parsing is done"); return true; @@ -443,7 +445,7 @@ public class ProxyConnectionFactory extends DetectorConnectionFactory public void onUpgradeTo(ByteBuffer prefilled) { if (LOG.isDebugEnabled()) - LOG.debug("Proxy v2 copying prefilled buffer {}", prefilled); + LOG.debug("Proxy v2 copying prefilled buffer {}", BufferUtil.toDetailString(prefilled)); if (BufferUtil.hasContent(prefilled)) BufferUtil.append(_buffer, prefilled); } From d27f4ee556a4982144f9354793c629b31399fd52 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Thu, 6 Feb 2020 14:11:58 +0100 Subject: [PATCH 07/27] Fixes #4550 XmlConfiguration named parameters Fixed #4550 named parameters with a moderate refactor. The named parameter matching was duplicated, only considering number of args and not applied to call arguments. This refactor puts all the behaviour in common methods and reorders the arguments to match parameters. Signed-off-by: Greg Wilkins --- .../eclipse/jetty/xml/XmlConfiguration.java | 331 +++++++-------- .../jetty/xml/AnnotatedTestConfiguration.java | 44 ++ .../jetty/xml/XmlConfigurationTest.java | 397 ++++++++++++------ 3 files changed, 467 insertions(+), 305 deletions(-) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index fde042b1b30..f5ca7e9fa9f 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -24,6 +24,7 @@ import java.io.StringReader; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; +import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -37,11 +38,11 @@ import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -51,7 +52,6 @@ import java.util.Queue; import java.util.ServiceLoader; import java.util.Set; -import org.eclipse.jetty.util.ArrayUtil; import org.eclipse.jetty.util.LazyList; import org.eclipse.jetty.util.Loader; import org.eclipse.jetty.util.MultiException; @@ -412,39 +412,13 @@ public class XmlConfiguration int index = 0; if (obj == null && oClass != null) { - index = _root.size(); - Map namedArgMap = new HashMap<>(); - - List arguments = new LinkedList<>(); - for (int i = 0; i < _root.size(); i++) - { - Object o = _root.get(i); - if (o instanceof String) - continue; - - XmlParser.Node node = (XmlParser.Node)o; - if (node.getTag().equals("Arg")) - { - String namedAttribute = node.getAttribute("name"); - Object value = value(null, (XmlParser.Node)o); - if (namedAttribute != null) - namedArgMap.put(namedAttribute, value); - arguments.add(value); - } - else - { - index = i; - break; - } - } - try { - obj = construct(oClass, arguments.toArray(), namedArgMap); + obj = construct(oClass, new NamedArgs(null, XmlConfiguration.getNodes(_root, "Arg"))); } catch (NoSuchMethodException x) { - throw new IllegalStateException(String.format("No constructor %s(%s,%s) in %s", oClass, arguments, namedArgMap, _configuration)); + throw new IllegalStateException(String.format("No maatching constructor %s in %s", oClass, _configuration)); } } if (id != null) @@ -916,7 +890,6 @@ public class XmlConfiguration String id = aoeNode.getString("Id"); String name = aoeNode.getString("Name"); String clazz = aoeNode.getString("Class"); - List args = aoeNode.getList("Arg"); Class oClass; if (clazz != null) @@ -937,7 +910,7 @@ public class XmlConfiguration try { - Object nobj = call(oClass, name, obj, args.toArray(new Object[0])); + Object nobj = call(oClass, name, obj, new NamedArgs(obj, aoeNode.getNodes("Arg"))); if (id != null) _configuration.getIdMap().put(id, nobj); configure(nobj, node, aoeNode.getNext()); @@ -949,7 +922,7 @@ public class XmlConfiguration } } - private Object call(Class oClass, String methodName, Object obj, Object[] arg) throws InvocationTargetException, NoSuchMethodException + private Object call(Class oClass, String methodName, Object obj, NamedArgs args) throws InvocationTargetException, NoSuchMethodException { Objects.requireNonNull(oClass, "Class cannot be null"); Objects.requireNonNull(methodName, "Method name cannot be null"); @@ -961,7 +934,8 @@ public class XmlConfiguration { if (!method.getName().equals(methodName)) continue; - if (method.getParameterCount() != arg.length) + Object[] arguments = args.applyTo(method); + if (arguments == null) continue; if (Modifier.isStatic(method.getModifiers()) != (obj == null)) continue; @@ -970,34 +944,7 @@ public class XmlConfiguration try { - return invokeMethod(method, obj, arg); - } - catch (IllegalAccessException | IllegalArgumentException e) - { - LOG.ignore(e); - } - } - - // Lets look for a method with varargs arguments - Object[] argsWithVarargs = null; - for (Method method : oClass.getMethods()) - { - if (!method.getName().equals(methodName)) - continue; - if (method.getParameterCount() != arg.length + 1) - continue; - if (!method.getParameterTypes()[arg.length].isArray()) - continue; - if (Modifier.isStatic(method.getModifiers()) != (obj == null)) - continue; - if ((obj == null) && method.getDeclaringClass() != oClass) - continue; - - if (argsWithVarargs == null) - argsWithVarargs = ArrayUtil.addToArray(arg, new Object[0], Object.class); - try - { - return invokeMethod(method, obj, argsWithVarargs); + return invokeMethod(method, obj, arguments); } catch (IllegalAccessException | IllegalArgumentException e) { @@ -1020,33 +967,16 @@ public class XmlConfiguration AttrOrElementNode aoeNode = new AttrOrElementNode(obj, node, "Id", "Class", "Arg"); String id = aoeNode.getString("Id"); String clazz = aoeNode.getString("Class"); - List argNodes = aoeNode.getNodes("Arg"); if (LOG.isDebugEnabled()) LOG.debug("XML new " + clazz); Class oClass = Loader.loadClass(clazz); - // Find the elements - Map namedArgMap = new HashMap<>(); - List arguments = new LinkedList<>(); - for (XmlParser.Node child : argNodes) - { - String namedAttribute = child.getAttribute("name"); - Object value = value(obj, child); - if (namedAttribute != null) - { - // named arguments - namedArgMap.put(namedAttribute, value); - } - // raw arguments - arguments.add(value); - } - Object nobj; try { - nobj = construct(oClass, arguments.toArray(), namedArgMap); + nobj = construct(oClass, new NamedArgs(obj, aoeNode.getNodes("Arg"))); } catch (NoSuchMethodException e) { @@ -1061,80 +991,19 @@ public class XmlConfiguration return nobj; } - private Object construct(Class klass, Object[] arguments, Map namedArgMap) throws InvocationTargetException, NoSuchMethodException + private Object construct(Class klass, NamedArgs args) throws InvocationTargetException, NoSuchMethodException { Objects.requireNonNull(klass, "Class cannot be null"); - Objects.requireNonNull(namedArgMap, "Named Argument Map cannot be null"); + Objects.requireNonNull(args, "Named list cannot be null"); + constructors: for (Constructor constructor : klass.getConstructors()) { - if (arguments == null) - { - // null arguments in .newInstance() is allowed - if (constructor.getParameterCount() != 0) - continue; - } - else if (constructor.getParameterCount() != arguments.length) - { - continue; - } - try { - if (arguments == null || arguments.length == 0) - { - if (LOG.isDebugEnabled()) - LOG.debug("Invoking constructor, no arguments"); - return invokeConstructor(constructor); - } - - if (namedArgMap.isEmpty()) - { - if (LOG.isDebugEnabled()) - LOG.debug("Invoking constructor, no XML parameter mapping"); + Object[] arguments = args.applyTo(constructor); + if (arguments != null) return invokeConstructor(constructor, arguments); - } - - Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); - if (parameterAnnotations == null || parameterAnnotations.length == 0) - { - if (LOG.isDebugEnabled()) - LOG.debug("Invoking constructor, no parameter annotations"); - return invokeConstructor(constructor, arguments); - } - - int count = 0; - Object[] swizzled = new Object[arguments.length]; - for (Annotation[] annotations : parameterAnnotations) - { - for (Annotation annotation : annotations) - { - if (annotation instanceof Name) - { - Name param = (Name)annotation; - if (namedArgMap.containsKey(param.value())) - { - if (LOG.isDebugEnabled()) - LOG.debug("Mapping named parameter {} in position {}", param.value(), count); - swizzled[count] = namedArgMap.get(param.value()); - } - else - { - if (LOG.isDebugEnabled()) - LOG.debug("Mapping argument {} in position {}", arguments[count], count); - swizzled[count] = arguments[count]; - } - ++count; - } - else - { - if (LOG.isDebugEnabled()) - LOG.debug("Skipping parameter annotated with {}", annotation); - } - } - } - - return invokeConstructor(constructor, swizzled); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { @@ -1777,40 +1646,146 @@ public class XmlConfiguration public List getNodes(String elementName) { - String attrName = StringUtil.asciiToLowerCase(elementName); - final List values = new ArrayList<>(); - - String attr = _node.getAttribute(attrName); - if (attr != null) - { - for (String a : StringUtil.csvSplit(null, attr, 0, attr.length())) - { - // create a fake node - XmlParser.Node n = new XmlParser.Node(null, elementName, null); - n.add(a); - values.add(n); - } - } - - for (int i = 0; i < _next; i++) - { - Object o = _node.get(i); - if (!(o instanceof XmlParser.Node)) - continue; - XmlParser.Node n = (XmlParser.Node)o; - - if (elementName.equals(n.getTag())) - { - if (attr != null) - throw new IllegalStateException("Cannot have attr '" + attrName + "' and element '" + elementName + "'"); - - values.add(n); - } - } - - return values; + return XmlConfiguration.getNodes(_node, elementName); } } + + private class NamedArgs + { + final List _arguments; + final List _names; + + NamedArgs(Object obj, List args) throws Exception + { + _arguments = new ArrayList<>(); + _names = new ArrayList<>(); + for (XmlParser.Node child : args) + { + _arguments.add(value(obj, child)); + _names.add(child.getAttribute("name")); + } + } + + NamedArgs(List arguments, List names) + { + _arguments = arguments; + _names = names; + } + + Object[] applyTo(Executable executable) + { + Object[] args = matchArgsToParameters(executable); + if (args == null) + { + // Could this be an empty varargs match? + int count = executable.getParameterCount(); + if (count > 0 && executable.getParameterTypes()[count - 1].isArray()) + args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); + } + return args; + } + + NamedArgs asEmptyVarArgs(Class varArgType) + { + List arguments = new ArrayList<>(_arguments); + arguments.add(Array.newInstance(varArgType.getComponentType(), 0)); + List names = new ArrayList<>(_names); + names.add(null); + return new NamedArgs(arguments, names); + } + + Object[] matchArgsToParameters(Executable executable) + { + int count = executable.getParameterCount(); + + // No match of wrong number of parameters + if (count != _arguments.size()) + return null; + + // Handle no parameter case + if (count == 0) + return new Object[0]; + + // If no arg names are specified, keep the arg order + if (_names.stream().noneMatch(Objects::nonNull)) + return _arguments.toArray(new Object[0]); + + // If we don't have any parameters with names, then no match + Annotation[][] parameterAnnotations = executable.getParameterAnnotations(); + if (parameterAnnotations == null || parameterAnnotations.length == 0) + return null; + + // Find the position of all named parameters from the executable + Map position = new HashMap<>(); + int p = 0; + for (Annotation[] paramAnnotation : parameterAnnotations) + { + Integer pos = p++; + Arrays.stream(paramAnnotation) + .filter(Name.class::isInstance) + .map(Name.class::cast) + .findFirst().ifPresent(n -> position.put(n.value(), pos)); + } + + List arguments = new ArrayList<>(_arguments); + List names = new ArrayList<>(_names); + // Map the actual arguments to the names + for (p = 0; p < count; p++) + { + String name = names.get(p); + if (name != null) + { + Integer pos = position.get(name); + if (pos == null) + return null; + if (pos != p) + { + // adjust position of parameter + arguments.add(pos, arguments.remove(p)); + names.add(pos, names.remove(p)); + p = Math.min(p, pos); + } + } + } + return arguments.toArray(new Object[0]); + } + } + } + + private static List getNodes(XmlParser.Node node, String elementName) + { + String attrName = StringUtil.asciiToLowerCase(elementName); + final List values = new ArrayList<>(); + + String attr = node.getAttribute(attrName); + if (attr != null) + { + for (String a : StringUtil.csvSplit(null, attr, 0, attr.length())) + { + // create a fake node + XmlParser.Node n = new XmlParser.Node(null, elementName, null); + n.add(a); + values.add(n); + } + } + + for (int i = 0; i < node.size(); i++) + { + Object o = node.get(i); + if (!(o instanceof XmlParser.Node)) + continue; + XmlParser.Node n = (XmlParser.Node)o; + + if (elementName.equals(n.getTag())) + { + if (attr != null) + throw new IllegalStateException("Cannot have attr '" + attrName + "' and element '" + elementName + "'"); + + values.add(n); + } + } + + return values; } /** diff --git a/jetty-xml/src/test/java/org/eclipse/jetty/xml/AnnotatedTestConfiguration.java b/jetty-xml/src/test/java/org/eclipse/jetty/xml/AnnotatedTestConfiguration.java index bb50abcc987..d114fc3b78a 100644 --- a/jetty-xml/src/test/java/org/eclipse/jetty/xml/AnnotatedTestConfiguration.java +++ b/jetty-xml/src/test/java/org/eclipse/jetty/xml/AnnotatedTestConfiguration.java @@ -41,6 +41,18 @@ public class AnnotatedTestConfiguration { } + public AnnotatedTestConfiguration(Integer test) + { + // exists to make constructor matching harder + throw new UnsupportedOperationException("Should not be called"); + } + + public AnnotatedTestConfiguration(Integer one, Integer two, Integer three) + { + // exists to make constructor matching harder + throw new UnsupportedOperationException("Should not be called"); + } + public AnnotatedTestConfiguration(@Name("first") String first, @Name("second") String second, @Name("third") String third) { this.first = first; @@ -48,6 +60,38 @@ public class AnnotatedTestConfiguration this.third = third; } + public AnnotatedTestConfiguration(Long one, Long two, Long three) + { + // exists to make constructor matching harder + throw new UnsupportedOperationException("Should not be called"); + } + + public void setAll(Integer one, Integer two, Integer three) + { + // exists to make method matching harder + throw new UnsupportedOperationException("Should not be called"); + } + + public void setAll(@Name("first") String first, @Name("second") String second, @Name("third") String third) + { + this.first = first; + this.second = second; + this.third = third; + } + + public void setAll(long one, long two, long three) + { + // exists to make method matching harder + throw new UnsupportedOperationException("Should not be called"); + } + + public void setVarArgs(String first, String... theRest) + { + this.first = first; + this.second = theRest.length > 0 ? theRest[0] : null; + this.third = theRest.length > 1 ? theRest[1] : null; + } + public String getFirst() { return first; diff --git a/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java b/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java index 99b859ecada..e730d35af1d 100644 --- a/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java +++ b/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java @@ -35,6 +35,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; @@ -45,6 +46,11 @@ import org.eclipse.jetty.util.resource.PathResource; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; import org.xml.sax.SAXException; import static java.nio.charset.StandardCharsets.UTF_8; @@ -67,9 +73,17 @@ public class XmlConfigurationTest { public WorkDir workDir; - protected String[] _configure = new String[]{ - "org/eclipse/jetty/xml/configureWithAttr.xml", "org/eclipse/jetty/xml/configureWithElements.xml" - }; + public static class ScenarioProvider implements ArgumentsProvider + { + @Override + public Stream provideArguments(ExtensionContext context) + { + return Stream.of( + "org/eclipse/jetty/xml/configureWithAttr.xml", + "org/eclipse/jetty/xml/configureWithElements.xml" + ).map(Arguments::of); + } + } private static final String STRING_ARRAY_XML = "String1String2"; private static final String INT_ARRAY_XML = "12"; @@ -82,170 +96,166 @@ public class XmlConfigurationTest configuration.configure(); } - @Test - public void testPassedObject() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPassedObject(String configure) throws Exception { - for (String configure : _configure) - { - Map properties = new HashMap<>(); - properties.put("whatever", "xxx"); - TestConfiguration.VALUE = 77; - URL url = XmlConfigurationTest.class.getClassLoader().getResource(configure); - XmlConfiguration configuration = new XmlConfiguration(url); - TestConfiguration tc = new TestConfiguration("tc"); - configuration.getProperties().putAll(properties); - configuration.configure(tc); + Map properties = new HashMap<>(); + properties.put("whatever", "xxx"); + TestConfiguration.VALUE = 77; + URL url = XmlConfigurationTest.class.getClassLoader().getResource(configure); + XmlConfiguration configuration = new XmlConfiguration(url); + TestConfiguration tc = new TestConfiguration("tc"); + configuration.getProperties().putAll(properties); + configuration.configure(tc); - assertEquals("SetValue", tc.testObject, "Set String"); - assertEquals(2, tc.testInt, "Set Type"); + assertEquals("SetValue", tc.testObject, "Set String"); + assertEquals(2, tc.testInt, "Set Type"); - assertEquals(18080, tc.propValue); + assertEquals(18080, tc.propValue); - assertEquals("PutValue", tc.get("Test"), "Put"); - assertEquals("2", tc.get("TestDft"), "Put dft"); - assertEquals(2, tc.get("TestInt"), "Put type"); + assertEquals("PutValue", tc.get("Test"), "Put"); + assertEquals("2", tc.get("TestDft"), "Put dft"); + assertEquals(2, tc.get("TestInt"), "Put type"); - assertEquals("PutValue", tc.get("Trim"), "Trim"); - assertNull(tc.get("Null"), "Null"); - assertNull(tc.get("NullTrim"), "NullTrim"); + assertEquals("PutValue", tc.get("Trim"), "Trim"); + assertNull(tc.get("Null"), "Null"); + assertNull(tc.get("NullTrim"), "NullTrim"); - assertEquals(1.2345, tc.get("ObjectTrim"), "ObjectTrim"); - assertEquals("-1String", tc.get("Objects"), "Objects"); - assertEquals("-1String", tc.get("ObjectsTrim"), "ObjectsTrim"); - assertEquals("\n PutValue\n ", tc.get("String"), "String"); - assertEquals("", tc.get("NullString"), "NullString"); - assertEquals("\n ", tc.get("WhiteSpace"), "WhiteSpace"); - assertEquals("\n 1.2345\n ", tc.get("ObjectString"), "ObjectString"); - assertEquals("-1String", tc.get("ObjectsString"), "ObjectsString"); - assertEquals("-1\n String", tc.get("ObjectsWhiteString"), "ObjectsWhiteString"); + assertEquals(1.2345, tc.get("ObjectTrim"), "ObjectTrim"); + assertEquals("-1String", tc.get("Objects"), "Objects"); + assertEquals("-1String", tc.get("ObjectsTrim"), "ObjectsTrim"); + assertEquals("\n PutValue\n ", tc.get("String"), "String"); + assertEquals("", tc.get("NullString"), "NullString"); + assertEquals("\n ", tc.get("WhiteSpace"), "WhiteSpace"); + assertEquals("\n 1.2345\n ", tc.get("ObjectString"), "ObjectString"); + assertEquals("-1String", tc.get("ObjectsString"), "ObjectsString"); + assertEquals("-1\n String", tc.get("ObjectsWhiteString"), "ObjectsWhiteString"); - assertEquals(System.getProperty("user.dir") + "/stuff", tc.get("SystemProperty"), "SystemProperty"); - assertEquals(System.getenv("HOME"), tc.get("Env"), "Env"); + assertEquals(System.getProperty("user.dir") + "/stuff", tc.get("SystemProperty"), "SystemProperty"); + assertEquals(System.getenv("HOME"), tc.get("Env"), "Env"); - assertEquals("xxx", tc.get("Property"), "Property"); + assertEquals("xxx", tc.get("Property"), "Property"); - assertEquals("Yes", tc.get("Called"), "Called"); + assertEquals("Yes", tc.get("Called"), "Called"); - assertTrue(TestConfiguration.called); + assertTrue(TestConfiguration.called); - assertEquals("Blah", tc.oa[0], "oa[0]"); - assertEquals("1.2.3.4:5678", tc.oa[1], "oa[1]"); - assertEquals(1.2345, tc.oa[2], "oa[2]"); - assertNull(tc.oa[3], "oa[3]"); + assertEquals("Blah", tc.oa[0], "oa[0]"); + assertEquals("1.2.3.4:5678", tc.oa[1], "oa[1]"); + assertEquals(1.2345, tc.oa[2], "oa[2]"); + assertNull(tc.oa[3], "oa[3]"); - assertEquals(1, tc.ia[0], "ia[0]"); - assertEquals(2, tc.ia[1], "ia[1]"); - assertEquals(3, tc.ia[2], "ia[2]"); - assertEquals(0, tc.ia[3], "ia[3]"); + assertEquals(1, tc.ia[0], "ia[0]"); + assertEquals(2, tc.ia[1], "ia[1]"); + assertEquals(3, tc.ia[2], "ia[2]"); + assertEquals(0, tc.ia[3], "ia[3]"); - TestConfiguration tc2 = tc.nested; - assertNotNull(tc2); - assertEquals(true, tc2.get("Arg"), "Called(bool)"); + TestConfiguration tc2 = tc.nested; + assertNotNull(tc2); + assertEquals(true, tc2.get("Arg"), "Called(bool)"); - assertNull(tc.get("Arg"), "nested config"); - assertEquals(true, tc2.get("Arg"), "nested config"); + assertNull(tc.get("Arg"), "nested config"); + assertEquals(true, tc2.get("Arg"), "nested config"); - assertEquals("Call1", tc2.testObject, "nested config"); - assertEquals(4, tc2.testInt, "nested config"); - assertEquals("http://www.eclipse.com/", tc2.url.toString(), "nested call"); + assertEquals("Call1", tc2.testObject, "nested config"); + assertEquals(4, tc2.testInt, "nested config"); + assertEquals("http://www.eclipse.com/", tc2.url.toString(), "nested call"); - assertEquals(tc.testField1, 77, "static to field"); - assertEquals(tc.testField2, 2, "field to field"); - assertEquals(TestConfiguration.VALUE, 42, "literal to static"); + assertEquals(tc.testField1, 77, "static to field"); + assertEquals(tc.testField2, 2, "field to field"); + assertEquals(TestConfiguration.VALUE, 42, "literal to static"); - assertEquals(((Map)configuration.getIdMap().get("map")).get("key0"), "value0"); - assertEquals(((Map)configuration.getIdMap().get("map")).get("key1"), "value1"); - } + assertEquals(((Map)configuration.getIdMap().get("map")).get("key0"), "value0"); + assertEquals(((Map)configuration.getIdMap().get("map")).get("key1"), "value1"); } - @Test - public void testNewObject() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testNewObject(String configure) throws Exception { - for (String configure : _configure) + TestConfiguration.VALUE = 71; + Map properties = new HashMap<>(); + properties.put("whatever", "xxx"); + + URL url = XmlConfigurationTest.class.getClassLoader().getResource(configure); + final AtomicInteger count = new AtomicInteger(0); + XmlConfiguration configuration = new XmlConfiguration(url) { - TestConfiguration.VALUE = 71; - Map properties = new HashMap<>(); - properties.put("whatever", "xxx"); - - URL url = XmlConfigurationTest.class.getClassLoader().getResource(configure); - final AtomicInteger count = new AtomicInteger(0); - XmlConfiguration configuration = new XmlConfiguration(url) + @Override + public void initializeDefaults(Object object) { - @Override - public void initializeDefaults(Object object) + if (object instanceof TestConfiguration) { - if (object instanceof TestConfiguration) - { - count.incrementAndGet(); - ((TestConfiguration)object).setNested(null); - ((TestConfiguration)object).setTestString("NEW DEFAULT"); - } + count.incrementAndGet(); + ((TestConfiguration)object).setNested(null); + ((TestConfiguration)object).setTestString("NEW DEFAULT"); } - }; - configuration.getProperties().putAll(properties); - TestConfiguration tc = (TestConfiguration)configuration.configure(); + } + }; + configuration.getProperties().putAll(properties); + TestConfiguration tc = (TestConfiguration)configuration.configure(); - assertEquals(3, count.get()); + assertEquals(3, count.get()); - assertEquals("NEW DEFAULT", tc.getTestString()); - assertEquals("nested", tc.getNested().getTestString()); - assertEquals("NEW DEFAULT", tc.getNested().getNested().getTestString()); + assertEquals("NEW DEFAULT", tc.getTestString()); + assertEquals("nested", tc.getNested().getTestString()); + assertEquals("NEW DEFAULT", tc.getNested().getNested().getTestString()); - assertEquals("SetValue", tc.testObject, "Set String"); - assertEquals(2, tc.testInt, "Set Type"); + assertEquals("SetValue", tc.testObject, "Set String"); + assertEquals(2, tc.testInt, "Set Type"); - assertEquals(18080, tc.propValue); + assertEquals(18080, tc.propValue); - assertEquals("PutValue", tc.get("Test"), "Put"); - assertEquals("2", tc.get("TestDft"), "Put dft"); - assertEquals(2, tc.get("TestInt"), "Put type"); + assertEquals("PutValue", tc.get("Test"), "Put"); + assertEquals("2", tc.get("TestDft"), "Put dft"); + assertEquals(2, tc.get("TestInt"), "Put type"); - assertEquals("PutValue", tc.get("Trim"), "Trim"); - assertNull(tc.get("Null"), "Null"); - assertNull(tc.get("NullTrim"), "NullTrim"); + assertEquals("PutValue", tc.get("Trim"), "Trim"); + assertNull(tc.get("Null"), "Null"); + assertNull(tc.get("NullTrim"), "NullTrim"); - assertEquals(1.2345, tc.get("ObjectTrim"), "ObjectTrim"); - assertEquals("-1String", tc.get("Objects"), "Objects"); - assertEquals("-1String", tc.get("ObjectsTrim"), "ObjectsTrim"); - assertEquals("\n PutValue\n ", tc.get("String"), "String"); - assertEquals("", tc.get("NullString"), "NullString"); - assertEquals("\n ", tc.get("WhiteSpace"), "WhiteSpace"); - assertEquals("\n 1.2345\n ", tc.get("ObjectString"), "ObjectString"); - assertEquals("-1String", tc.get("ObjectsString"), "ObjectsString"); - assertEquals("-1\n String", tc.get("ObjectsWhiteString"), "ObjectsWhiteString"); + assertEquals(1.2345, tc.get("ObjectTrim"), "ObjectTrim"); + assertEquals("-1String", tc.get("Objects"), "Objects"); + assertEquals("-1String", tc.get("ObjectsTrim"), "ObjectsTrim"); + assertEquals("\n PutValue\n ", tc.get("String"), "String"); + assertEquals("", tc.get("NullString"), "NullString"); + assertEquals("\n ", tc.get("WhiteSpace"), "WhiteSpace"); + assertEquals("\n 1.2345\n ", tc.get("ObjectString"), "ObjectString"); + assertEquals("-1String", tc.get("ObjectsString"), "ObjectsString"); + assertEquals("-1\n String", tc.get("ObjectsWhiteString"), "ObjectsWhiteString"); - assertEquals(System.getProperty("user.dir") + "/stuff", tc.get("SystemProperty"), "SystemProperty"); - assertEquals("xxx", tc.get("Property"), "Property"); + assertEquals(System.getProperty("user.dir") + "/stuff", tc.get("SystemProperty"), "SystemProperty"); + assertEquals("xxx", tc.get("Property"), "Property"); - assertEquals("Yes", tc.get("Called"), "Called"); + assertEquals("Yes", tc.get("Called"), "Called"); - assertTrue(TestConfiguration.called); + assertTrue(TestConfiguration.called); - assertEquals("Blah", tc.oa[0], "oa[0]"); - assertEquals("1.2.3.4:5678", tc.oa[1], "oa[1]"); - assertEquals(1.2345, tc.oa[2], "oa[2]"); - assertNull(tc.oa[3], "oa[3]"); + assertEquals("Blah", tc.oa[0], "oa[0]"); + assertEquals("1.2.3.4:5678", tc.oa[1], "oa[1]"); + assertEquals(1.2345, tc.oa[2], "oa[2]"); + assertNull(tc.oa[3], "oa[3]"); - assertEquals(1, tc.ia[0], "ia[0]"); - assertEquals(2, tc.ia[1], "ia[1]"); - assertEquals(3, tc.ia[2], "ia[2]"); - assertEquals(0, tc.ia[3], "ia[3]"); + assertEquals(1, tc.ia[0], "ia[0]"); + assertEquals(2, tc.ia[1], "ia[1]"); + assertEquals(3, tc.ia[2], "ia[2]"); + assertEquals(0, tc.ia[3], "ia[3]"); - TestConfiguration tc2 = tc.nested; - assertNotNull(tc2); - assertEquals(true, tc2.get("Arg"), "Called(bool)"); + TestConfiguration tc2 = tc.nested; + assertNotNull(tc2); + assertEquals(true, tc2.get("Arg"), "Called(bool)"); - assertNull(tc.get("Arg"), "nested config"); - assertEquals(true, tc2.get("Arg"), "nested config"); + assertNull(tc.get("Arg"), "nested config"); + assertEquals(true, tc2.get("Arg"), "nested config"); - assertEquals("Call1", tc2.testObject, "nested config"); - assertEquals(4, tc2.testInt, "nested config"); - assertEquals("http://www.eclipse.com/", tc2.url.toString(), "nested call"); + assertEquals("Call1", tc2.testObject, "nested config"); + assertEquals(4, tc2.testInt, "nested config"); + assertEquals("http://www.eclipse.com/", tc2.url.toString(), "nested call"); - assertEquals(71, tc.testField1, "static to field"); - assertEquals(2, tc.testField2, "field to field"); - assertEquals(42, TestConfiguration.VALUE, "literal to static"); - } + assertEquals(71, tc.testField1, "static to field"); + assertEquals(2, tc.testField2, "field to field"); + assertEquals(42, TestConfiguration.VALUE, "literal to static"); } public XmlConfiguration asXmlConfiguration(String rawXml) throws IOException, SAXException @@ -648,6 +658,139 @@ public class XmlConfigurationTest assertEquals("arg3", atc.getNested().getThird(), "nested third parameter not wired correctly"); } + @Test + public void testCallNamedInjection() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " arg1 " + + " arg2 " + + " arg3 " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("arg1", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("arg2", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("arg3", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallNamedInjectionOrdered() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " arg1 " + + " arg2 " + + " arg3 " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("arg1", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("arg2", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("arg3", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallNamedInjectionUnOrdered() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " arg1 " + + " arg3 " + + " arg2 " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("arg1", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("arg2", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("arg3", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallNamedInjectionOrderedMixed() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " arg1 " + + " arg2 " + + " arg3 " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("arg1", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("arg2", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("arg3", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallNamedInjectionUnorderedMixed() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " arg3 " + + " arg2 " + + " arg1 " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("arg1", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("arg2", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("arg3", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallVarArgs() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " " + + " one " + + " twothree " + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("one", atc.getFirst(), "first parameter not wired correctly"); + assertEquals("two", atc.getSecond(), "second parameter not wired correctly"); + assertEquals("three", atc.getThird(), "third parameter not wired correctly"); + } + + @Test + public void testCallMissingVarArgs() throws Exception + { + XmlConfiguration xmlConfiguration = asXmlConfiguration( + "" + + " arg1 " + + " arg2 " + + " arg3 " + + " " + + " one" + + " " + + ""); + + AnnotatedTestConfiguration atc = (AnnotatedTestConfiguration)xmlConfiguration.configure(); + + assertEquals("one", atc.getFirst(), "first parameter not wired correctly"); + assertNull(atc.getSecond()); + assertNull(atc.getThird()); + } + @Test public void testArgumentsGetIgnoredMissingDTD() throws Exception { From 2c8d405b83f0b690e4a703c5c1ffefc9ce062026 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Thu, 6 Feb 2020 18:55:42 +0100 Subject: [PATCH 08/27] Fixes #4550 XmlConfiguration named parameters Do not match a missing varArgs executable is there is a matching method with no varArgs. Signed-off-by: Greg Wilkins --- .../eclipse/jetty/xml/XmlConfiguration.java | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index f5ca7e9fa9f..4e38c478550 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -414,7 +414,7 @@ public class XmlConfiguration { try { - obj = construct(oClass, new NamedArgs(null, XmlConfiguration.getNodes(_root, "Arg"))); + obj = construct(oClass, new NamedArgs(null, oClass, XmlConfiguration.getNodes(_root, "Arg"))); } catch (NoSuchMethodException x) { @@ -910,7 +910,7 @@ public class XmlConfiguration try { - Object nobj = call(oClass, name, obj, new NamedArgs(obj, aoeNode.getNodes("Arg"))); + Object nobj = call(oClass, name, obj, new NamedArgs(obj, oClass, aoeNode.getNodes("Arg"))); if (id != null) _configuration.getIdMap().put(id, nobj); configure(nobj, node, aoeNode.getNext()); @@ -976,7 +976,7 @@ public class XmlConfiguration Object nobj; try { - nobj = construct(oClass, new NamedArgs(obj, aoeNode.getNodes("Arg"))); + nobj = construct(oClass, new NamedArgs(obj, oClass, aoeNode.getNodes("Arg"))); } catch (NoSuchMethodException e) { @@ -1652,11 +1652,13 @@ public class XmlConfiguration private class NamedArgs { + final Class _class; final List _arguments; final List _names; - NamedArgs(Object obj, List args) throws Exception + NamedArgs(Object obj, Class oClass, List args) throws Exception { + _class = oClass; _arguments = new ArrayList<>(); _names = new ArrayList<>(); for (XmlParser.Node child : args) @@ -1666,8 +1668,9 @@ public class XmlConfiguration } } - NamedArgs(List arguments, List names) + private NamedArgs(List arguments, List names) { + _class = null; _arguments = arguments; _names = names; } @@ -1675,12 +1678,31 @@ public class XmlConfiguration Object[] applyTo(Executable executable) { Object[] args = matchArgsToParameters(executable); - if (args == null) + if (args == null && _class != null) { // Could this be an empty varargs match? int count = executable.getParameterCount(); if (count > 0 && executable.getParameterTypes()[count - 1].isArray()) - args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); + { + try + { + // Does a non varargs method exist? + Class[] types = Arrays.copyOf(executable.getParameterTypes(), count - 1); + if (executable instanceof Constructor) + _class.getConstructor(types); + else + _class.getMethod(((Method)executable).getName(), types); + } + catch (NoSuchMethodException e) + { + // There is not a no varArgs alternative so let's try a null varArgs match + args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); + } + catch (Exception e) + { + LOG.ignore(e); + } + } } return args; } From f50c2654b91fda2a0dc5f19ab7b0d5f820738c67 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Thu, 6 Feb 2020 21:17:58 +0100 Subject: [PATCH 09/27] Fixes #4541 Large Headers Added a HEADER_OVERFLOW result as per review Signed-off-by: Greg Wilkins --- .../jetty/client/http/HttpSenderOverHTTP.java | 7 ++++ .../org/eclipse/jetty/http/HttpGenerator.java | 6 ++- .../jetty/http/HttpGeneratorClientTest.java | 37 +++++++++++++++++++ .../http/HttpGeneratorServerHTTPTest.java | 6 +++ .../jetty/http/HttpGeneratorServerTest.java | 32 ++++++++++++++++ .../org/eclipse/jetty/http/HttpTester.java | 6 +++ .../eclipse/jetty/server/HttpConnection.java | 23 +++++------- 7 files changed, 102 insertions(+), 15 deletions(-) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java index 386c7852434..44314749ee8 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java @@ -27,6 +27,7 @@ import org.eclipse.jetty.client.HttpRequest; import org.eclipse.jetty.client.HttpRequestException; import org.eclipse.jetty.client.HttpSender; import org.eclipse.jetty.client.api.ContentProvider; +import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpGenerator; import org.eclipse.jetty.http.HttpURI; import org.eclipse.jetty.http.MetaData; @@ -36,6 +37,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.IteratingCallback; +import static org.eclipse.jetty.http.HttpStatus.INTERNAL_SERVER_ERROR_500; + public class HttpSenderOverHTTP extends HttpSender { private final HttpGenerator generator = new HttpGenerator(); @@ -225,6 +228,10 @@ public class HttpSenderOverHTTP extends HttpSender headerBuffer = httpClient.getByteBufferPool().acquire(httpClient.getRequestBufferSize(), false); break; } + case HEADER_OVERFLOW: + { + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Request header too large"); + } case NEED_CHUNK: { chunkBuffer = httpClient.getByteBufferPool().acquire(HttpGenerator.CHUNK_SIZE, false); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java index 20b73f39fb8..8be21bff0d3 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java @@ -74,6 +74,7 @@ public class HttpGenerator NEED_CHUNK, // Need a small chunk buffer of CHUNK_SIZE NEED_INFO, // Need the request/response metadata info NEED_HEADER, // Need a buffer to build HTTP headers into + HEADER_OVERFLOW, // The header buffer overflowed NEED_CHUNK_TRAILER, // Need a large chunk buffer for last chunk and trailers FLUSH, // The buffers previously generated should be flushed CONTINUE, // Continue generating the message @@ -262,7 +263,8 @@ public class HttpGenerator } catch (BufferOverflowException e) { - throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Request header too large", e); + LOG.ignore(e); + return Result.HEADER_OVERFLOW; } catch (Exception e) { @@ -446,7 +448,7 @@ public class HttpGenerator catch (BufferOverflowException e) { LOG.ignore(e); - return Result.NEED_HEADER; + return Result.HEADER_OVERFLOW; } catch (Exception e) { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java index 492a77de0f2..3a1437a293f 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class HttpGeneratorClientTest @@ -122,6 +123,42 @@ public class HttpGeneratorClientTest assertThat(out, Matchers.not(Matchers.containsString("Null:"))); } + @Test + public void testHeaderOverflow() throws Exception + { + HttpGenerator gen = new HttpGenerator(); + + Info info = new Info("GET", "/index.html"); + info.getFields().add("Host", "localhost"); + info.getFields().add("Field", "SomeWhatLongValue"); + info.setHttpVersion(HttpVersion.HTTP_1_0); + + HttpGenerator.Result result = gen.generateRequest(info, null, null, null, true); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + + ByteBuffer header = BufferUtil.allocate(16); + result = gen.generateRequest(info, header, null, null, true); + assertEquals(HttpGenerator.Result.HEADER_OVERFLOW, result); + + header = BufferUtil.allocate(2048); + result = gen.generateRequest(info, header, null, null, true); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertFalse(gen.isChunking()); + String out = BufferUtil.toString(header); + BufferUtil.clear(header); + + result = gen.generateResponse(null, false, null, null, null, false); + assertEquals(HttpGenerator.Result.SHUTDOWN_OUT, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + assertFalse(gen.isChunking()); + + assertEquals(0, gen.getContentPrepared()); + assertThat(out, Matchers.containsString("GET /index.html HTTP/1.0")); + assertThat(out, Matchers.not(Matchers.containsString("Content-Length"))); + assertThat(out, Matchers.containsString("Field: SomeWhatLongValue")); + } + @Test public void testPOSTRequestNoContent() throws Exception { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java index c42f15e4aff..cfe3cd9442b 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java @@ -155,6 +155,12 @@ public class HttpGeneratorServerHTTPTest header = BufferUtil.allocate(2048); continue; + case HEADER_OVERFLOW: + if (header.capacity() >= 8192) + throw new BadMessageException(500, "Header too large"); + header = BufferUtil.allocate(8192); + continue; + case NEED_CHUNK: chunk = BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); continue; diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java index 5574bcf5b9f..bb32ae7331a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java @@ -110,6 +110,38 @@ public class HttpGeneratorServerTest assertThat(response, containsString("\r\n0123456789")); } + @Test + public void testHeaderOverflow() throws Exception + { + HttpGenerator gen = new HttpGenerator(); + + MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_1, 302, null, new HttpFields(), 0); + info.getFields().add("Location", "http://somewhere/else"); + + HttpGenerator.Result result = gen.generateResponse(info, false, null, null, null, true); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + + ByteBuffer header = BufferUtil.allocate(16); + result = gen.generateResponse(info, false, header, null, null, true); + assertEquals(HttpGenerator.Result.HEADER_OVERFLOW, result); + + header = BufferUtil.allocate(8096); + result = gen.generateResponse(info, false, header, null, null, true); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + String response = BufferUtil.toString(header); + BufferUtil.clear(header); + + result = gen.generateResponse(null, false, null, null, null, false); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + + assertEquals(0, gen.getContentPrepared()); + + assertThat(response, containsString("HTTP/1.1 302 Found")); + assertThat(response, containsString("Location: http://somewhere/else")); + } + @Test public void test204() throws Exception { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpTester.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpTester.java index 96a59bc446b..06b9d005a44 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpTester.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpTester.java @@ -451,6 +451,12 @@ public class HttpTester header = BufferUtil.allocate(8192); continue; + case HEADER_OVERFLOW: + if (header.capacity() >= 32 * 1024) + throw new BadMessageException(500, "Header too large"); + header = BufferUtil.allocate(32 * 1024); + continue; + case NEED_CHUNK: chunk = BufferUtil.allocate(HttpGenerator.CHUNK_SIZE); continue; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java index 15c357703f3..26f7cb550db 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java @@ -757,19 +757,16 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http case NEED_HEADER: { - int size; - if (_header == null) - { - size = Math.min(_config.getResponseHeaderSize(), _config.getOutputBufferSize()); - } - else - { - if (_header.capacity() >= _config.getResponseHeaderSize()) - throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large"); - size = _config.getResponseHeaderSize(); - _bufferPool.release(_header); - } - _header = _bufferPool.acquire(size, HEADER_BUFFER_DIRECT); + _header = _bufferPool.acquire(Math.min(_config.getResponseHeaderSize(), _config.getOutputBufferSize()), HEADER_BUFFER_DIRECT); + continue; + } + + case HEADER_OVERFLOW: + { + if (_header.capacity() >= _config.getResponseHeaderSize()) + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large"); + _bufferPool.release(_header); + _header = _bufferPool.acquire(_config.getResponseHeaderSize(), HEADER_BUFFER_DIRECT); continue; } case NEED_CHUNK: From 20621b76fb48333ca17efb4f0ad17bb8441b93a4 Mon Sep 17 00:00:00 2001 From: Lachlan Roberts Date: Fri, 7 Feb 2020 21:32:43 +1100 Subject: [PATCH 10/27] Issue #4537 - fix potential spin when discarding in WebSocketConnection Signed-off-by: Lachlan Roberts --- .../jetty/websocket/common/io/AbstractWebSocketConnection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java b/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java index c93330d7d56..a9535a9d932 100644 --- a/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java +++ b/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java @@ -497,7 +497,7 @@ public abstract class AbstractWebSocketConnection extends AbstractConnection imp case DISCARD: if (LOG.isDebugEnabled()) LOG.debug("Discarded buffer - {}", BufferUtil.toDetailString(buffer)); - buffer.clear(); + BufferUtil.clear(buffer); break; case SUSPEND: From ebed3e5b38309b90f86f03fa3ec6c2473e1087f0 Mon Sep 17 00:00:00 2001 From: Olivier Lamy Date: Thu, 13 Feb 2020 11:13:20 +1000 Subject: [PATCH 11/27] Issue #4562 remove deprecated jetty-runner (#4563) Signed-off-by: olivier lamy --- .../asciidoc/distribution-guide/index.adoc | 1 - .../distribution-guide/runner/chapter.adoc | 24 - .../runner/jetty-runner.adoc | 349 ---------- jetty-runner/pom.xml | 135 ---- jetty-runner/src/it/settings.xml | 36 -- .../it/test-jar-manifest/invoker.properties | 1 - jetty-runner/src/it/test-jar-manifest/pom.xml | 59 -- .../src/it/test-jar-manifest/postbuild.groovy | 10 - .../java/org/eclipse/jetty/runner/Runner.java | 595 ------------------ .../eclipse/jetty/runner/package-info.java | 23 - jetty-runner/src/main/resources/MANIFEST.MF | 1 - pom.xml | 1 - 12 files changed, 1235 deletions(-) delete mode 100644 jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc delete mode 100644 jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc delete mode 100644 jetty-runner/pom.xml delete mode 100644 jetty-runner/src/it/settings.xml delete mode 100644 jetty-runner/src/it/test-jar-manifest/invoker.properties delete mode 100644 jetty-runner/src/it/test-jar-manifest/pom.xml delete mode 100644 jetty-runner/src/it/test-jar-manifest/postbuild.groovy delete mode 100644 jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java delete mode 100644 jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java delete mode 100644 jetty-runner/src/main/resources/MANIFEST.MF diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc index 20a8c1a9022..679a3217a41 100644 --- a/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc +++ b/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc @@ -74,5 +74,4 @@ include::jndi/chapter.adoc[] include::alpn/chapter.adoc[] include::fastcgi/chapter.adoc[] include::extras/chapter.adoc[] -include::runner/chapter.adoc[] include::tuning/chapter.adoc[] diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc deleted file mode 100644 index 946b526331b..00000000000 --- a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[runner]] -== Jetty Runner - -This chapter explains how to use the `jetty-runner` to run your webapps without needing an installation of Jetty. - -include::jetty-runner.adoc[] diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc deleted file mode 100644 index e0f36400658..00000000000 --- a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc +++ /dev/null @@ -1,349 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-runner]] -=== Use Jetty Without an Installed Distribution - -The idea of the `jetty-runner` is extremely simple – run a webapp directly from the command line using a single jar file and as much default configuration as possible. -Of course, if your webapp is not as straightforward, the `jetty-runner` has command line options which allow you to customize the execution environment. - -[[jetty-runner-preparation]] -==== Preparation - -You will need the `jetty-runner` jar: - -1. Download the `jetty-runner` jar available at https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-runner/[Maven Central]. - -==== Deploying a Simple Context - -Let's assume we have a very simple webapp that does not need any resources from its environment, nor any configuration apart from the defaults. -Starting it is as simple as performing the following: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar simple.war -.... - -This will start Jetty on port 8080, and deploy the webapp to `/`. - -Your webapp does not have to be packed into a war, you can deploy a webapp that is a directory instead in the same way: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar simple -.... - -In fact, the webapp does not have to be a war or even a directory, it can simply be a Jetty link:#using-context-provider[context xml] file that describes your webapp: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar simple-context.xml -.... - -____ -[NOTE] -When using a context xml file, the application being deployed is not even required to be a fully-fledged webapp. -It can simply be a Jetty link:#what-is-a-context[context]. -____ - -By default, `jetty-runner` implements all Configuration Classes so that users can set up and deploy new instances with as little configuration as possible. -If you wish to only implement certain Configuration Classes, they will need to be defined in the context xml for the webapp/context. -The default Configuration Classes are: - -`org.eclipse.jetty.webapp.WebInfConfiguration` -`org.eclipse.jetty.webapp.WebXmlConfiguration` -`org.eclipse.jetty.webapp.MetaInfConfiguration` -`org.eclipse.jetty.webapp.FragmentConfiguration` -`org.eclipse.jetty.webapp.JettyWebXmlConfiguration` -`org.eclipse.jetty.plus.webapp.EnvConfiguration` -`org.eclipse.jetty.plus.webapp.PlusConfiguration` -`org.eclipse.jetty.annotations.AnnotationConfiguration` - -You can learn more about implementing specific Configuration Classes link:https://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-configurations[here.] - -==== Deploying Multiple Contexts - -If you have more than one webapp that must be deployed, simply provide them all on the command line. -You can control the context paths for them using the `--path` parameter. -Here's an example of deploying 2 wars (although either or both of them could be unpacked directories instead): - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --path /one my1.war --path /two my2.war -.... - -If you have context xml files that describe your webapps, you can fully configure your webapps in them and hence you won't need to use the command line switches. -Just provide the list of context files like so: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar my-first-context.xml my-second-context.xml my-third-context.xml -.... - -____ -[NOTE] -Switched used on the command line override configuration file settings. -So, for example, you could set the context path for the webapp inside the context xml file, and use the `--path` switch to override it on the command line. -____ - - -===== Changing the Default Port - -By default the `jetty-runner` will listen on port 8080. -You can easily change this on the command line using the `--port` command. -Here's an example that runs our simple.war on port 9090: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --port 9090 simple.war -.... - -===== Using jetty.xml Files - -Instead of, or in addition to, using command line switches, you can use one or more `jetty.xml` files to configure the environment for your webapps. -Here's an example where we apply two different `jetty.xml` files: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --config jetty.xml --config jetty-https.xml simple.war -.... - -[[runner-configuration-reference]] -==== Full Configuration Reference - -You can see the fill set of configuration options using the `--help` switch: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --help -.... - -Here's what the output will look like: - -[source, plain, subs="{sub-order}"] ----- - -Usage: java [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] -Server opts: - --version - display version and exit - --log file - request log filename (with optional 'yyyy_mm_dd' wildcard - --out file - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard - --host name|ip - interface to listen on (default is all interfaces) - --port n - port to listen on (default 8080) - --stop-port n - port to listen for stop command (or -DSTOP.PORT=n) - --stop-key n - security string for stop command (required if --stop-port is present) (or -DSTOP.KEY=n) - [--jar file]*n - each tuple specifies an extra jar to be added to the classloader - [--lib dir]*n - each tuple specifies an extra directory of jars to be added to the classloader - [--classes dir]*n - each tuple specifies an extra directory of classes to be added to the classloader - --stats [unsecure|realm.properties] - enable stats gathering servlet context - [--config file]*n - each tuple specifies the name of a jetty xml config file to apply (in the order defined) -Context opts: - [[--path /path] context]*n - WAR file, web app dir or context xml file, optionally with a context path ----- - -===== Printing the Version -Print out the version of Jetty and then exit immediately. - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --version -.... - -===== Configuring a Request Log -Cause Jetty to write a request log with the given name. -If the file is prefixed with `yyyy_mm_dd` then the file will be automatically rolled over. -Note that for finer grained configuration of the link:{JDURL}/org/eclipse/jetty/server/NCSARequestLog.html[request log], you will need to use a Jetty xml file instead. - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --log yyyy_mm_dd-requests.log my.war -.... - -===== Configuring the Output Log -Redirect the output of jetty logging to the named file. -If the file is prefixed with `yyyy_mm_dd` then the file will be automatically rolled over. - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --out yyyy_mm_dd-output.log my.war -.... - -===== Configuring the Interface for HTTP -Like Jetty standalone, the default is for the connectors to listen on all interfaces on a machine. -You can control that by specifying the name or ip address of the particular interface you wish to use with the `--host` argument: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --host 192.168.22.19 my.war -.... - -===== Configuring the Port for HTTP -The default port number is 8080. -To link:#how-to-configure-connectors[configure a https connector], use a Jetty xml config file instead. - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --port 9090 my.war -.... - -===== Configuring Stop -You can configure a port number for Jetty to listen on for a stop command, so you are able to stop it from a different terminal. -This requires the use of a "secret" key, to prevent malicious or accidental termination. -Use the `--stop-port` and `--stop-key` (or `-DSTOP.PORT=` and `-DSTOP.KEY=`, respectively) parameters as arguments to the `jetty-runner`: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --stop-port 8181 --stop-key abc123 -.... - -Then, to stop Jetty from a different terminal, you need to supply the same port and key information. -For this you'll either need a local installation of Jetty, the link:#jetty-maven-plugin[jetty-maven-plugin], the link:#jetty-ant[jetty-ant plugin], or a custom class. -Here's how to use a Jetty installation to perform a stop: - -[source, screen, subs="{sub-order}"] -.... -> java -jar start.jar -DSTOP.PORT=8181 -DSTOP.KEY=abc123 --stop -.... - -===== Configuring the Container Classpath -With a local installation of Jetty, you add jars and classes to the container's classpath by putting them in the `{$jetty.base}/lib` directory. -With the `jetty-runner`, you can use the `--lib`, `--jar` and `--classes` arguments instead to achieve the same thing. - -`--lib` adds the location of a directory which contains jars to add to the container classpath. -You can add 1 or more. -Here's an example of configuring 2 directories: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --lib /usr/local/external/lib --lib $HOME/external-other/lib my.war -.... - -`--jar` adds a single jar file to the container classpath. -You can add 1 or more. -Here's an example of configuring 3 extra jars: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --jar /opt/stuff/jars/jar1.jar --jar $HOME/jars/jar2.jar --jar /usr/local/proj/jars/jar3.jar my.war -.... - -`--classes` add the location of a directory containing classes to add to the container classpath. -You can add 1 or more. -Here's an example of configuring a single extra classes dir: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --classes /opt/stuff/classes my.war -.... - -____ -[NOTE] -When using the `--jar` and/or `--lib` arguments, by default these will *not* be inspected for `META-INF` information such as `META-INF/resources`, `META-INF/web-fragment.xml`, or `META-INF/taglib.tld`. -If you require these jar files inspected you will need to define the link:https://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-context-attributes[jar pattern in your context xml file]. -Jetty-Runner automatically provides and appends a suitable pattern for jtsl taglibs (this pattern is different than the one in the standard Jetty distribution). -____ - - -===== Gathering Statistics -If statistics gathering is enabled, then they are viewable by surfing to the context `/stats`. -You may optionally protect access to that context with a password. -Here's an example of enabling statistics, with no password protection: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --stats unsecure my.war -.... - -If we wished to protect access to the `/stats` context, we would provide the location of a Jetty realm configuration file containing authentication and authorization information. -For example, we could use the following example realm file from the Jetty distribution: - -[source, screen, subs="{sub-order}"] -.... -jetty: MD5:164c88b302622e17050af52c89945d44,user -admin: CRYPT:adpexzg3FUZAk,server-administrator,content-administrator,admin -other: OBF:1xmk1w261u9r1w1c1xmq,user -plain: plain,user -user: password,user -# This entry is for digest auth. The credential is a MD5 hash of username:realmname:password -digest: MD5:6e120743ad67abfbc385bc2bb754e297,user -.... - -Assuming we've copied it into the local directory, we would apply it like so - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --stats realm.properties my.war -.... - -After navigating to http://localhost:8080/ a few times, we can point to the stats servlet on http://localhost:8080/stats to see the output: - -.... -Statistics: -Statistics gathering started 1490627ms ago - -Requests: -Total requests: 9 -Active requests: 1 -Max active requests: 1 -Total requests time: 63 -Mean request time: 7.875 -Max request time: 26 -Request time standard deviation: 8.349764752888037 - - -Dispatches: -Total dispatched: 9 -Active dispatched: 1 -Max active dispatched: 1 -Total dispatched time: 63 -Mean dispatched time: 7.875 -Max dispatched time: 26 -Dispatched time standard deviation: 8.349764752888037 -Total requests suspended: 0 -Total requests expired: 0 -Total requests resumed: 0 - - -Responses: -1xx responses: 0 -2xx responses: 7 -3xx responses: 1 -4xx responses: 0 -5xx responses: 0 -Bytes sent total: 1453 - - -Connections: -org.eclipse.jetty.server.ServerConnector@203822411 -Protocols:http/1.1 -Statistics gathering started 1490606ms ago -Total connections: 7 -Current connections open: 1 -Max concurrent connections open: 2 -Total connections duration: 72883 -Mean connection duration: 12147.166666666666 -Max connection duration: 65591 -Connection duration standard deviation: 23912.40292977684 -Total messages in: 7 -Total messages out: 7 - - -Memory: -Heap memory usage: 49194840 bytes -Non-heap memory usage: 12611696 bytes -.... diff --git a/jetty-runner/pom.xml b/jetty-runner/pom.xml deleted file mode 100644 index 96a76bed6f8..00000000000 --- a/jetty-runner/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - org.eclipse.jetty - jetty-project - 10.0.0-SNAPSHOT - - 4.0.0 - jetty-runner - Jetty :: Runner - - - target/distribution - ${project.groupId}.runner - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - unpack-dependencies - prepare-package - - unpack-dependencies - - - ** - **/MANIFEST.MF,META-INF/*.RSA,META-INF/*.DSA,META-INF/*.SF,module-info.class - ${project.build.directory}/classes - false - true - - - - - - org.apache.maven.plugins - maven-invoker-plugin - - - integration-test - integration-test - - install - integration-test - verify - - - - - - ${maven.dependency.plugin.version} - - - clean - - - - - - - - org.neo4j.build.plugins - clirr-maven-plugin - - - true - - - - org.apache.felix - maven-bundle-plugin - - - true - - ${project.build.directory}/NON_USED_MANIFEST - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/MANIFEST.MF - - org.eclipse.jetty.runner.Runner - - - - - - - - - - - org.eclipse.jetty - jetty-plus - ${project.version} - - - org.eclipse.jetty - jetty-annotations - ${project.version} - - - org.eclipse.jetty - jetty-jaas - ${project.version} - - - org.eclipse.jetty.websocket - websocket-jetty-server - ${project.version} - - - org.eclipse.jetty - jetty-jndi - ${project.version} - - - org.eclipse.jetty - apache-jsp - ${project.version} - - - org.eclipse.jetty - apache-jstl - ${project.version} - - - diff --git a/jetty-runner/src/it/settings.xml b/jetty-runner/src/it/settings.xml deleted file mode 100644 index d64bdb89034..00000000000 --- a/jetty-runner/src/it/settings.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - it-repo - - true - - - - local.central - @localRepositoryUrl@ - - true - - - true - - - - - - local.central - @localRepositoryUrl@ - - true - - - true - - - - - - diff --git a/jetty-runner/src/it/test-jar-manifest/invoker.properties b/jetty-runner/src/it/test-jar-manifest/invoker.properties deleted file mode 100644 index 86f8ef2b751..00000000000 --- a/jetty-runner/src/it/test-jar-manifest/invoker.properties +++ /dev/null @@ -1 +0,0 @@ -invoker.goals = generate-resources diff --git a/jetty-runner/src/it/test-jar-manifest/pom.xml b/jetty-runner/src/it/test-jar-manifest/pom.xml deleted file mode 100644 index d619f71a186..00000000000 --- a/jetty-runner/src/it/test-jar-manifest/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - 4.0.0 - - org.eclipse.jetty.its - jetty-runner-it-test - 1.0.0-SNAPSHOT - war - - - UTF-8 - - - - - - org.eclipse.jetty - jetty-runner - @project.version@ - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - @maven.dependency.plugin.version@ - - - copy-jetty-runner - generate-resources - - copy - - - - - org.eclipse.jetty - jetty-runner - @project.version@ - jar - false - ${project.build.directory}/ - jetty-runner.jar - - - false - true - - - - - - - - diff --git a/jetty-runner/src/it/test-jar-manifest/postbuild.groovy b/jetty-runner/src/it/test-jar-manifest/postbuild.groovy deleted file mode 100644 index da1a6d99e3c..00000000000 --- a/jetty-runner/src/it/test-jar-manifest/postbuild.groovy +++ /dev/null @@ -1,10 +0,0 @@ -import java.util.jar.* - -File artifact = new File( basedir, "target/jetty-runner.jar" ) -assert artifact.exists() - -JarFile jar = new JarFile( artifact ); - -Attributes manifest = jar.getManifest().getMainAttributes(); - -assert manifest.getValue( new Attributes.Name( "Main-Class" ) ).equals( "org.eclipse.jetty.runner.Runner" ) diff --git a/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java b/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java deleted file mode 100644 index 991fc300257..00000000000 --- a/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java +++ /dev/null @@ -1,595 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.runner; - -import java.io.IOException; -import java.io.PrintStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import org.eclipse.jetty.io.ConnectionStatistics; -import org.eclipse.jetty.security.ConstraintMapping; -import org.eclipse.jetty.security.ConstraintSecurityHandler; -import org.eclipse.jetty.security.HashLoginService; -import org.eclipse.jetty.security.authentication.BasicAuthenticator; -import org.eclipse.jetty.server.AbstractConnector; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.CustomRequestLog; -import org.eclipse.jetty.server.Handler; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.ShutdownMonitor; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.server.handler.DefaultHandler; -import org.eclipse.jetty.server.handler.HandlerCollection; -import org.eclipse.jetty.server.handler.StatisticsHandler; -import org.eclipse.jetty.server.session.SessionHandler; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.servlet.StatisticsServlet; -import org.eclipse.jetty.util.RolloverFileOutputStream; -import org.eclipse.jetty.util.StringUtil; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.resource.Resource; -import org.eclipse.jetty.util.security.Constraint; -import org.eclipse.jetty.webapp.MetaInfConfiguration; -import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.jetty.xml.XmlConfiguration; - -/** - * Runner - *

- * Combine jetty classes into a single executable jar and run webapps based on the args to it. - * - * @deprecated No replacement provided or available. Migrate to jetty-home (and use {@code ${jetty.base}} directory). - */ -@Deprecated -public class Runner -{ - private static final Logger LOG = Log.getLogger(Runner.class); - - public static final String[] PLUS_CONFIGURATION_CLASSES = - { - org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), - org.eclipse.jetty.annotations.AnnotationConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName() - }; - public static final String CONTAINER_INCLUDE_JAR_PATTERN = ".*/jetty-runner-[^/]*\\.jar$"; - public static final String DEFAULT_CONTEXT_PATH = "/"; - public static final int DEFAULT_PORT = 8080; - - protected Server _server; - protected URLClassLoader _classLoader; - protected Classpath _classpath = new Classpath(); - protected ContextHandlerCollection _contexts; - protected String _logFile; - protected ArrayList _configFiles; - protected boolean _enableStats = false; - protected String _statsPropFile; - - /** - * Classpath - */ - public class Classpath - { - private List _classpath = new ArrayList<>(); - - public void addJars(Resource lib) throws IOException - { - if (lib == null || !lib.exists()) - throw new IllegalStateException("No such lib: " + lib); - - String[] list = lib.list(); - if (list == null) - return; - - for (String path : list) - { - if (".".equals(path) || "..".equals(path)) - continue; - - try (Resource item = lib.addPath(path)) - { - if (item.isDirectory()) - addJars(item); - else - { - String lowerCasePath = path.toLowerCase(Locale.ENGLISH); - if (lowerCasePath.endsWith(".jar") || - lowerCasePath.endsWith(".zip")) - { - _classpath.add(item.getURI()); - } - } - } - } - } - - public void addPath(Resource path) - { - if (path == null || !path.exists()) - throw new IllegalStateException("No such path: " + path); - _classpath.add(path.getURI()); - } - - public URI[] asArray() - { - return _classpath.toArray(new URI[0]); - } - } - - public Runner() - { - } - - /** - * Generate helpful usage message and exit - * - * @param error the error header - */ - public void usage(String error) - { - if (error != null) - System.err.println("ERROR: " + error); - System.err.println("Usage: java [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] "); - System.err.println("Server opts:"); - System.err.println(" --version - display version and exit"); - System.err.println(" --log file - request log filename (with optional 'yyyy_mm_dd' wildcard"); - System.err.println(" --out file - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard"); - System.err.println(" --host name|ip - interface to listen on (default is all interfaces)"); - System.err.println(" --port n - port to listen on (default 8080)"); - System.err.println(" --stop-port n - port to listen for stop command (or -DSTOP.PORT=n)"); - System.err.println(" --stop-key n - security string for stop command (required if --stop-port is present) (or -DSTOP.KEY=n)"); - System.err.println(" [--jar file]*n - each tuple specifies an extra jar to be added to the classloader"); - System.err.println(" [--lib dir]*n - each tuple specifies an extra directory of jars to be added to the classloader"); - System.err.println(" [--classes dir]*n - each tuple specifies an extra directory of classes to be added to the classloader"); - System.err.println(" --stats [unsecure|realm.properties] - enable stats gathering servlet context"); - System.err.println(" [--config file]*n - each tuple specifies the name of a jetty xml config file to apply (in the order defined)"); - System.err.println("Context opts:"); - System.err.println(" [[--path /path] context]*n - WAR file, web app dir or context xml file, optionally with a context path"); - System.exit(1); - } - - /** - * Generate version message and exit - */ - public void version() - { - System.err.println("org.eclipse.jetty.runner.Runner: " + Server.getVersion()); - System.exit(1); - } - - /** - * Configure a jetty instance and deploy the webapps presented as args - * - * @param args the command line arguments - * @throws Exception if unable to configure - */ - public void configure(String[] args) throws Exception - { - // handle classpath bits first so we can initialize the log mechanism. - for (int i = 0; i < args.length; i++) - { - if ("--lib".equals(args[i])) - { - try (Resource lib = Resource.newResource(args[++i])) - { - if (!lib.exists() || !lib.isDirectory()) - usage("No such lib directory " + lib); - _classpath.addJars(lib); - } - } - else if ("--jar".equals(args[i])) - { - try (Resource jar = Resource.newResource(args[++i])) - { - if (!jar.exists() || jar.isDirectory()) - usage("No such jar " + jar); - _classpath.addPath(jar); - } - } - else if ("--classes".equals(args[i])) - { - try (Resource classes = Resource.newResource(args[++i])) - { - if (!classes.exists() || !classes.isDirectory()) - usage("No such classes directory " + classes); - _classpath.addPath(classes); - } - } - else if (args[i].startsWith("--")) - i++; - } - - initClassLoader(); - - LOG.info("Runner"); - LOG.debug("Runner classpath {}", _classpath); - - String contextPath = DEFAULT_CONTEXT_PATH; - boolean contextPathSet = false; - int port = DEFAULT_PORT; - String host = null; - int stopPort = Integer.getInteger("STOP.PORT", 0); - String stopKey = System.getProperty("STOP.KEY", null); - - boolean runnerServerInitialized = false; - - for (int i = 0; i < args.length; i++) - { - switch (args[i]) - { - case "--port": - port = Integer.parseInt(args[++i]); - break; - case "--host": - host = args[++i]; - break; - case "--stop-port": - stopPort = Integer.parseInt(args[++i]); - break; - case "--stop-key": - stopKey = args[++i]; - break; - case "--log": - _logFile = args[++i]; - break; - case "--out": - String outFile = args[++i]; - PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1)); - LOG.info("Redirecting stderr/stdout to " + outFile); - System.setErr(out); - System.setOut(out); - break; - case "--path": - contextPath = args[++i]; - contextPathSet = true; - break; - case "--config": - if (_configFiles == null) - _configFiles = new ArrayList<>(); - _configFiles.add(args[++i]); - break; - case "--lib": - ++i;//skip - - break; - case "--jar": - ++i; //skip - - break; - case "--classes": - ++i;//skip - - break; - case "--stats": - _enableStats = true; - _statsPropFile = args[++i]; - _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); - break; - default: - // process system property type argument so users can use in second args part - if (args[i].startsWith("-D")) - { - String[] sysProps = args[i].substring(2).split("=", 2); - if ("STOP.KEY".equals(sysProps[0])) - { - stopKey = sysProps[1]; - break; - } - else if ("STOP.PORT".equals(sysProps[0])) - { - stopPort = Integer.parseInt(sysProps[1]); - break; - } - } - -// process contexts - - if (!runnerServerInitialized) // log handlers not registered, server maybe not created, etc - { - if (_server == null) // server not initialized yet - { - // build the server - _server = new Server(); - } - - //apply jetty config files if there are any - if (_configFiles != null) - { - for (String cfg : _configFiles) - { - try (Resource resource = Resource.newResource(cfg)) - { - XmlConfiguration xmlConfiguration = new XmlConfiguration(resource); - xmlConfiguration.configure(_server); - } - } - } - - //check that everything got configured, and if not, make the handlers - HandlerCollection handlers = (HandlerCollection)_server.getChildHandlerByClass(HandlerCollection.class); - if (handlers == null) - { - handlers = new HandlerCollection(); - _server.setHandler(handlers); - } - - //check if contexts already configured - _contexts = (ContextHandlerCollection)handlers.getChildHandlerByClass(ContextHandlerCollection.class); - if (_contexts == null) - { - _contexts = new ContextHandlerCollection(); - prependHandler(_contexts, handlers); - } - - if (_enableStats) - { - //if no stats handler already configured - if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) - { - StatisticsHandler statsHandler = new StatisticsHandler(); - - Handler oldHandler = _server.getHandler(); - statsHandler.setHandler(oldHandler); - _server.setHandler(statsHandler); - - ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats"); - statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/"); - statsContext.setSessionHandler(new SessionHandler()); - if (_statsPropFile != null) - { - final HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile); - Constraint constraint = new Constraint(); - constraint.setName("Admin Only"); - constraint.setRoles(new String[]{"admin"}); - constraint.setAuthenticate(true); - - ConstraintMapping cm = new ConstraintMapping(); - cm.setConstraint(constraint); - cm.setPathSpec("/*"); - - ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); - securityHandler.setLoginService(loginService); - securityHandler.setConstraintMappings(Collections.singletonList(cm)); - securityHandler.setAuthenticator(new BasicAuthenticator()); - statsContext.setSecurityHandler(securityHandler); - } - } - } - - //ensure a DefaultHandler is present - if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) - { - handlers.addHandler(new DefaultHandler()); - } - - //check a connector is configured to listen on - Connector[] connectors = _server.getConnectors(); - if (connectors == null || connectors.length == 0) - { - ServerConnector connector = new ServerConnector(_server); - connector.setPort(port); - if (host != null) - connector.setHost(host); - _server.addConnector(connector); - if (_enableStats) - connector.addBean(new ConnectionStatistics()); - } - else - { - if (_enableStats) - { - for (Connector connector : connectors) - { - ((AbstractConnector)connector).addBean(new ConnectionStatistics()); - } - } - } - - runnerServerInitialized = true; - } - - // Create a context - try (Resource ctx = Resource.newResource(args[i])) - { - if (!ctx.exists()) - usage("Context '" + ctx + "' does not exist"); - - if (contextPathSet && !(contextPath.startsWith("/"))) - contextPath = "/" + contextPath; - - // Configure the context - if (!ctx.isDirectory() && ctx.toString().toLowerCase(Locale.ENGLISH).endsWith(".xml")) - { - // It is a context config file - XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx); - xmlConfiguration.getIdMap().put("Server", _server); - ContextHandler handler = (ContextHandler)xmlConfiguration.configure(); - if (contextPathSet) - handler.setContextPath(contextPath); - _contexts.addHandler(handler); - String containerIncludeJarPattern = (String)handler.getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN); - if (containerIncludeJarPattern == null) - containerIncludeJarPattern = CONTAINER_INCLUDE_JAR_PATTERN; - else - { - if (!containerIncludeJarPattern.contains(CONTAINER_INCLUDE_JAR_PATTERN)) - { - containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + CONTAINER_INCLUDE_JAR_PATTERN; - } - } - - handler.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern); - - //check the configurations, if not explicitly set up, then configure all of them - if (handler instanceof WebAppContext) - { - WebAppContext wac = (WebAppContext)handler; - if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0) - wac.setConfigurationClasses(PLUS_CONFIGURATION_CLASSES); - } - } - else - { - // assume it is a WAR file - WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); - webapp.setConfigurationClasses(PLUS_CONFIGURATION_CLASSES); - webapp.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, - CONTAINER_INCLUDE_JAR_PATTERN); - } - } - //reset - contextPathSet = false; - contextPath = DEFAULT_CONTEXT_PATH; - break; - } - } - - if (_server == null) - usage("No Contexts defined"); - _server.setStopAtShutdown(true); - - switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) - { - case 1: - usage("Must specify --stop-key when --stop-port is specified"); - break; - - case 2: - usage("Must specify --stop-port when --stop-key is specified"); - break; - - case 3: - ShutdownMonitor monitor = ShutdownMonitor.getInstance(); - monitor.setPort(stopPort); - monitor.setKey(stopKey); - monitor.setExitVm(true); - break; - - default: - break; - } - - if (_logFile != null) - { - CustomRequestLog requestLog = new CustomRequestLog(_logFile); - _server.setRequestLog(requestLog); - } - } - - protected void prependHandler(Handler handler, HandlerCollection handlers) - { - if (handler == null || handlers == null) - return; - - Handler[] existing = handlers.getChildHandlers(); - Handler[] children = new Handler[existing.length + 1]; - children[0] = handler; - System.arraycopy(existing, 0, children, 1, existing.length); - handlers.setHandlers(children); - } - - public void run() throws Exception - { - _server.start(); - _server.join(); - } - - private URL toURL(URI uri) - { - try - { - return uri.toURL(); - } - catch (MalformedURLException e) - { - throw new RuntimeException(e); - } - } - - /** - * Establish a classloader with custom paths (if any) - */ - protected void initClassLoader() - { - URL[] paths = Arrays.stream(_classpath.asArray()).map(this::toURL).toArray(URL[]::new); - - if (_classLoader == null && paths.length > 0) - { - ClassLoader context = Thread.currentThread().getContextClassLoader(); - - if (context == null) - { - _classLoader = new URLClassLoader(paths); - } - else - { - _classLoader = new URLClassLoader(paths, context); - } - - Thread.currentThread().setContextClassLoader(_classLoader); - } - } - - public static void main(String[] args) - { - System.err.println("WARNING: jetty-runner is deprecated."); - System.err.println(" See Jetty Documentation for startup options"); - System.err.println(" https://www.eclipse.org/jetty/documentation/"); - - Runner runner = new Runner(); - - try - { - if (args.length > 0 && args[0].equalsIgnoreCase("--help")) - { - runner.usage(null); - } - else if (args.length > 0 && args[0].equalsIgnoreCase("--version")) - { - runner.version(); - } - else - { - runner.configure(args); - runner.run(); - } - } - catch (Exception e) - { - e.printStackTrace(); - runner.usage(null); - } - } -} diff --git a/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java b/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java deleted file mode 100644 index 8cf44e618e9..00000000000 --- a/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -/** - * Jetty Runner : Embedded Jetty Tool for running webapps directly - */ -package org.eclipse.jetty.runner; - diff --git a/jetty-runner/src/main/resources/MANIFEST.MF b/jetty-runner/src/main/resources/MANIFEST.MF deleted file mode 100644 index fa816753df9..00000000000 --- a/jetty-runner/src/main/resources/MANIFEST.MF +++ /dev/null @@ -1 +0,0 @@ -Comment: Jetty Runner diff --git a/pom.xml b/pom.xml index 8cc78b4e2f1..8e4ea9e1e34 100644 --- a/pom.xml +++ b/pom.xml @@ -132,7 +132,6 @@ examples jetty-quickstart jetty-distribution - jetty-runner jetty-http-spi jetty-osgi jetty-alpn From ab5005b9f746cfdc9fd223c098d9582c6d36f852 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Sun, 16 Feb 2020 09:43:31 +0100 Subject: [PATCH 12/27] Fixes #4575 Stopping Reserved Thread Fixes #4575 Stopping Reserved Thread by removing the `isRunning` check from `reservedWait`. The main run loop is also simplified to improve `isRunning` checks before the thread is put on the stack. Javadoc improved to explain each step. Signed-off-by: Greg Wilkins --- .../util/thread/ReservedThreadExecutor.java | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ReservedThreadExecutor.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ReservedThreadExecutor.java index 0bc982c266c..ef59ff2a6f8 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ReservedThreadExecutor.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ReservedThreadExecutor.java @@ -299,9 +299,6 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec while (true) { - if (!isRunning()) - return STOP; - try { Runnable task = _idleTime <= 0 ? _task.take() : _task.poll(_idleTime, _idleTimeUnit); @@ -333,23 +330,26 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec { // test and increment size BEFORE decrementing pending, // so that we don't have a race starting new pending. - while (true) + int size = _size.get(); + + // Are we stopped? + if (size < 0) + return; + + // Are we surplus to capacity? + if (size >= _capacity) { - int size = _size.get(); - if (size < 0) - return; - if (size >= _capacity) - { - if (LOG.isDebugEnabled()) - LOG.debug("{} size {} > capacity", this, size, _capacity); - if (_starting) - _pending.decrementAndGet(); - return; - } - if (_size.compareAndSet(size, size + 1)) - break; + if (LOG.isDebugEnabled()) + LOG.debug("{} size {} > capacity", this, size, _capacity); + if (_starting) + _pending.decrementAndGet(); + return; } + // If we cannot update size then recalculate + if (!_size.compareAndSet(size, size + 1)) + continue; + if (_starting) { if (LOG.isDebugEnabled()) @@ -362,7 +362,8 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec // that only effects the decision to keep other threads reserved. _stack.offerFirst(this); - // Wait for a task + // Once added to the stack, we must always wait for a job on the _task Queue + // and never return early, else we may leave a thread blocked offering a _task. Runnable task = reservedWait(); if (task == STOP) From 652428ad7040444d46888f652fb4a0b1a28c7832 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Sun, 16 Feb 2020 11:04:34 +0100 Subject: [PATCH 13/27] Tests #4573 X-Forwarded ordering Added tests for header ordering fixed cut-and-paste error of _for to _host Signed-off-by: Greg Wilkins --- .../server/ForwardedRequestCustomizer.java | 3 +- .../ForwardedRequestCustomizerTest.java | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ForwardedRequestCustomizer.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ForwardedRequestCustomizer.java index 93a69857792..4d224dfe3cb 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ForwardedRequestCustomizer.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ForwardedRequestCustomizer.java @@ -589,13 +589,14 @@ public class ForwardedRequestCustomizer implements Customizer } } + @SuppressWarnings("unused") public void handleHost(HttpField field) { if (getForwardedPortAsAuthority() && !StringUtil.isEmpty(getForwardedPortHeader())) { if (_host == null) _host = new PossiblyPartialHostPort(getLeftMost(field.getValue())); - else if (_for instanceof PortSetHostPort) + else if (_host instanceof PortSetHostPort) _host = new HostPort(HostPort.normalizeHost(getLeftMost(field.getValue())), _host.getPort()); } else if (_host == null) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java index 9a60e7f20d6..a6dfa9f58a2 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java @@ -397,6 +397,34 @@ public class ForwardedRequestCustomizerTest .requestURL("http://myhost:4444/") .remoteAddr("192.168.1.200").remotePort(0) ), + Arguments.of(new Request("X-Forwarded-* (all headers except server)") + .headers( + "GET / HTTP/1.1", + "Host: myhost", + "X-Forwarded-Proto: https", + "X-Forwarded-Host: www.example.com", + "X-Forwarded-Port: 4333", + "X-Forwarded-For: 8.5.4.3:2222" + ), + new Expectations() + .scheme("https").serverName("www.example.com").serverPort(4333) + .requestURL("https://www.example.com:4333/") + .remoteAddr("8.5.4.3").remotePort(2222) + ), + Arguments.of(new Request("X-Forwarded-* (all headers except server, port first)") + .headers( + "GET / HTTP/1.1", + "Host: myhost", + "X-Forwarded-Proto: https", + "X-Forwarded-Port: 4333", + "X-Forwarded-Host: www.example.com", + "X-Forwarded-For: 8.5.4.3:2222" + ), + new Expectations() + .scheme("https").serverName("www.example.com").serverPort(4333) + .requestURL("https://www.example.com:4333/") + .remoteAddr("8.5.4.3").remotePort(2222) + ), Arguments.of(new Request("X-Forwarded-* (all headers)") .headers( "GET / HTTP/1.1", @@ -427,6 +455,21 @@ public class ForwardedRequestCustomizerTest .requestURL("https://www.example.com:4333/") .remoteAddr("8.5.4.3").remotePort(2222) ), + Arguments.of(new Request("X-Forwarded-* (all headers reversed)") + .headers( + "GET / HTTP/1.1", + "Host: myhost", + "X-Forwarded-Server: fw.example.com", + "X-Forwarded-For: 8.5.4.3:2222", + "X-Forwarded-Port: 4333", + "X-Forwarded-Host: www.example.com", + "X-Forwarded-Proto: https" + ), + new Expectations() + .scheme("https").serverName("www.example.com").serverPort(4333) + .requestURL("https://www.example.com:4333/") + .remoteAddr("8.5.4.3").remotePort(2222) + ), Arguments.of(new Request("X-Forwarded-* (Server and Port)") .headers( "GET / HTTP/1.1", @@ -440,6 +483,19 @@ public class ForwardedRequestCustomizerTest .requestURL("http://fw.example.com:4333/") .remoteAddr("8.5.4.3").remotePort(2222) ), + Arguments.of(new Request("X-Forwarded-* (Port and Server)") + .headers( + "GET / HTTP/1.1", + "Host: myhost", + "X-Forwarded-Port: 4333", + "X-Forwarded-For: 8.5.4.3:2222", + "X-Forwarded-Server: fw.example.com" + ), + new Expectations() + .scheme("http").serverName("fw.example.com").serverPort(4333) + .requestURL("http://fw.example.com:4333/") + .remoteAddr("8.5.4.3").remotePort(2222) + ), // ================================================================= // Mixed Behavior From 612a70b5be152e4ba165367bbcc1fea58f2ee982 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Sun, 16 Feb 2020 22:17:13 +0100 Subject: [PATCH 14/27] =?UTF-8?q?Issue=20#4518=20-=C2=A0Add=20a=20mechanis?= =?UTF-8?q?m=20that=20allows=20running=20multiple=20protocols=20on=20the?= =?UTF-8?q?=20same=20port.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixed tests after merge. Signed-off-by: Simone Bordet --- .../jetty/server/DetectorConnectionTest.java | 30 +++++++------------ .../server/OptionalSslConnectionTest.java | 3 +- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java index 79bb28fecc2..f83212104bc 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java @@ -92,11 +92,10 @@ public class DetectorConnectionTest private String getResponseOverSsl(String request) throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); sslContextFactory.start(); SSLSocketFactory socketFactory = sslContextFactory.getSslContext().getSocketFactory(); @@ -222,11 +221,10 @@ public class DetectorConnectionTest @Test public void testDetectingSslProxyToHttpNoSslWithProxy() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); @@ -251,11 +249,10 @@ public class DetectorConnectionTest @Test public void testDetectingSslProxyToHttpWithSslNoProxy() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); @@ -276,11 +273,10 @@ public class DetectorConnectionTest @Test public void testDetectingSslProxyToHttpWithSslWithProxy() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); @@ -303,11 +299,10 @@ public class DetectorConnectionTest @Test public void testDetectionUnsuccessfulUpgradesToNextProtocol() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); @@ -328,11 +323,10 @@ public class DetectorConnectionTest @Test void testDetectorToNextDetector() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(http.getProtocol()); @@ -394,11 +388,10 @@ public class DetectorConnectionTest @Test void testDetectorWithProxyThatHasNoNextProto() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory(); @@ -421,11 +414,10 @@ public class DetectorConnectionTest @Test void testOptionalSsl() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConnectionFactory http = new HttpConnectionFactory(); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); @@ -449,11 +441,10 @@ public class DetectorConnectionTest @Test void testDetectorThatHasNoConfiguredNextProto() throws Exception { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); DetectorConnectionFactory detector = new DetectorConnectionFactory(ssl); @@ -621,11 +612,10 @@ public class DetectorConnectionTest @Test void testGeneratedProtocolNames() { - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java index 6f2d0cf0402..9135a4f0ba2 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java @@ -211,11 +211,10 @@ public class OptionalSslConnectionTest serverThreads.setName("server"); server = new Server(serverThreads); - String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); + String keystore = MavenTestingUtils.getTestResourceFile("keystore.p12").getAbsolutePath(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore); sslContextFactory.setKeyStorePassword("storepwd"); - sslContextFactory.setKeyManagerPassword("keypwd"); HttpConfiguration httpConfig = new HttpConfiguration(); HttpConnectionFactory http = new HttpConnectionFactory(httpConfig); From ed7f337856e4c9aa12d6824ff204546d9ab37b5e Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Mon, 17 Feb 2020 00:53:44 +0100 Subject: [PATCH 15/27] =?UTF-8?q?Issue=20#4518=20-=C2=A0Add=20a=20mechanis?= =?UTF-8?q?m=20that=20allows=20running=20multiple=20protocols=20on=20the?= =?UTF-8?q?=20same=20port.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Made test methods public, so that they will work fine in JDK 11 and JPMS. Signed-off-by: Simone Bordet --- .../jetty/server/DetectorConnectionTest.java | 22 +++++++++---------- .../server/OptionalSslConnectionTest.java | 2 +- .../jetty/server/ProxyConnectionTest.java | 6 ++--- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java index 6f99f24264b..e257431ea23 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DetectorConnectionTest.java @@ -326,7 +326,7 @@ public class DetectorConnectionTest } @Test - void testDetectorToNextDetector() throws Exception + public void testDetectorToNextDetector() throws Exception { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); @@ -357,7 +357,7 @@ public class DetectorConnectionTest } @Test - void testDetectorWithDetectionUnsuccessful() throws Exception + public void testDetectorWithDetectionUnsuccessful() throws Exception { AtomicBoolean detectionSuccessful = new AtomicBoolean(true); ProxyConnectionFactory proxy = new ProxyConnectionFactory(HttpVersion.HTTP_1_1.asString()); @@ -392,7 +392,7 @@ public class DetectorConnectionTest } @Test - void testDetectorWithProxyThatHasNoNextProto() throws Exception + public void testDetectorWithProxyThatHasNoNextProto() throws Exception { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); @@ -419,7 +419,7 @@ public class DetectorConnectionTest } @Test - void testOptionalSsl() throws Exception + public void testOptionalSsl() throws Exception { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); @@ -447,7 +447,7 @@ public class DetectorConnectionTest } @Test - void testDetectorThatHasNoConfiguredNextProto() throws Exception + public void testDetectorThatHasNoConfiguredNextProto() throws Exception { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); @@ -471,7 +471,7 @@ public class DetectorConnectionTest } @Test - void testDetectorWithNextProtocolThatDoesNotExist() throws Exception + public void testDetectorWithNextProtocolThatDoesNotExist() throws Exception { HttpConnectionFactory http = new HttpConnectionFactory(); ProxyConnectionFactory proxy = new ProxyConnectionFactory("does-not-exist"); @@ -506,7 +506,7 @@ public class DetectorConnectionTest } @Test - void testDetectingWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception + public void testDetectingWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception { ConnectionFactory.Detecting noUpgradeTo = new ConnectionFactory.Detecting() { @@ -573,7 +573,7 @@ public class DetectorConnectionTest } @Test - void testDetectorWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception + public void testDetectorWithNextProtocolThatDoesNotImplementUpgradeTo() throws Exception { ConnectionFactory noUpgradeTo = new ConnectionFactory() { @@ -619,7 +619,7 @@ public class DetectorConnectionTest } @Test - void testGeneratedProtocolNames() + public void testGeneratedProtocolNames() { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); SslContextFactory sslContextFactory = new SslContextFactory.Server(); @@ -635,13 +635,13 @@ public class DetectorConnectionTest } @Test - void testDetectorWithNoDetectingFails() + public void testDetectorWithNoDetectingFails() { assertThrows(IllegalArgumentException.class, DetectorConnectionFactory::new); } @Test - void testExerciseDetectorNotEnoughBytes() throws Exception + public void testExerciseDetectorNotEnoughBytes() throws Exception { ConnectionFactory.Detecting detectingNeverRecognizes = new ConnectionFactory.Detecting() { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java index 699081acff1..d1da9376c3b 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/OptionalSslConnectionTest.java @@ -206,7 +206,7 @@ public class OptionalSslConnectionTest } @Test - void testNextProtocolIsNotNullButNotConfiguredEither() throws Exception + public void testNextProtocolIsNotNullButNotConfiguredEither() throws Exception { QueuedThreadPool serverThreads = new QueuedThreadPool(); serverThreads.setName("server"); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java index 9aa38e3554d..7e1f6ab8cdf 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java @@ -189,7 +189,7 @@ public class ProxyConnectionTest @ParameterizedTest @MethodSource("requestProcessors") - void testSimple(RequestProcessor p) throws Exception + public void testSimple(RequestProcessor p) throws Exception { String request = "PROXY TCP 1.2.3.4 5.6.7.8 111 222\r\n" + "GET /path HTTP/1.1\n" + @@ -207,7 +207,7 @@ public class ProxyConnectionTest @ParameterizedTest @MethodSource("requestProcessors") - void testSimpleV2(RequestProcessor p) throws Exception + public void testSimpleV2(RequestProcessor p) throws Exception { String proxy = // Preamble @@ -243,7 +243,7 @@ public class ProxyConnectionTest @ParameterizedTest @MethodSource("requestProcessors") - void testMaxHeaderLengthV2(RequestProcessor p) throws Exception + public void testMaxHeaderLengthV2(RequestProcessor p) throws Exception { p.customize((connector) -> { From 01438e6f917cbf8ed1aa2e19abe732fade2acba0 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Mon, 17 Feb 2020 17:32:51 +0100 Subject: [PATCH 16/27] Code cleanup. Changed the way the test directory was created: it was based on a millisecond timestamp, but the tests run fast and it was possible that two tests were creating the directory within the same millisecond. Signed-off-by: Simone Bordet --- .../http/MultiPartFormInputStreamTest.java | 81 +++++++------------ 1 file changed, 29 insertions(+), 52 deletions(-) diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java index f2f96a7a8c2..48beb58d3a1 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java @@ -25,13 +25,14 @@ import java.io.IOException; import java.io.InputStream; import java.util.Base64; import java.util.Collection; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.MultipartConfigElement; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.Part; import org.eclipse.jetty.http.MultiPartFormInputStream.MultiPart; +import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; import org.junit.jupiter.api.Test; @@ -51,17 +52,14 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -/** - * MultiPartInputStreamTest - */ public class MultiPartFormInputStreamTest { + private static final AtomicInteger testCounter = new AtomicInteger(); private static final String FILENAME = "stuff.txt"; protected String _contentType = "multipart/form-data, boundary=AaB03x"; protected String _multi = createMultipartRequestString(FILENAME); - // TODO: move to testing dir concept - protected String _dirname = System.getProperty("java.io.tmpdir") + File.separator + "myfiles-" + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - protected File _tmpDir = new File(_dirname); + protected File _tmpDir = MavenTestingUtils.getTargetTestingDir(String.valueOf(testCounter.incrementAndGet())); + protected String _dirname = _tmpDir.getAbsolutePath(); public MultiPartFormInputStreamTest() { @@ -70,7 +68,6 @@ public class MultiPartFormInputStreamTest @Test public void testBadMultiPartRequest() - throws Exception { String boundary = "X0Y0"; String str = "--" + boundary + "\r\n" + @@ -89,14 +86,13 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); IOException x = assertThrows(IOException.class, - () -> mpis.getParts(), + mpis::getParts, "Incomplete Multipart"); assertThat(x.getMessage(), startsWith("Incomplete")); } @Test - public void testFinalBoundaryOnly() - throws Exception + public void testFinalBoundaryOnly() throws Exception { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; @@ -119,8 +115,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testEmpty() - throws Exception + public void testEmpty() throws Exception { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; @@ -139,8 +134,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testNoBoundaryRequest() - throws Exception + public void testNoBoundaryRequest() throws Exception { String str = "--\r\n" + "Content-Disposition: form-data; name=\"fileName\"\r\n" + @@ -200,8 +194,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testNonMultiPartRequest() - throws Exception + public void testNonMultiPartRequest() throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -214,7 +207,6 @@ public class MultiPartFormInputStreamTest @Test public void testNoBody() - throws Exception { String body = ""; @@ -225,13 +217,12 @@ public class MultiPartFormInputStreamTest _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, () -> mpis.getParts()); + IOException x = assertThrows(IOException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } @Test - public void testBodyAlreadyConsumed() - throws Exception + public void testBodyAlreadyConsumed() throws Exception { ServletInputStream is = new ServletInputStream() { @@ -272,7 +263,6 @@ public class MultiPartFormInputStreamTest @Test public void testWhitespaceBodyWithCRLF() - throws Exception { String whitespace = " \n\n\n\r\n\r\n\r\n\r\n"; @@ -282,13 +272,12 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, () -> mpis.getParts()); + IOException x = assertThrows(IOException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } @Test public void testWhitespaceBody() - throws Exception { String whitespace = " "; @@ -298,13 +287,12 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - IOException x = assertThrows(IOException.class, () -> mpis.getParts()); + IOException x = assertThrows(IOException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Missing initial")); } @Test - public void testLeadingWhitespaceBodyWithCRLF() - throws Exception + public void testLeadingWhitespaceBodyWithCRLF() throws Exception { String body = " \n\n\n\r\n\r\n\r\n\r\n" + "--AaB03x\r\n" + @@ -380,8 +368,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testNoLimits() - throws Exception + public void testNoLimits() throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -395,7 +382,6 @@ public class MultiPartFormInputStreamTest @Test public void testRequestTooBig() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -404,13 +390,12 @@ public class MultiPartFormInputStreamTest _tmpDir); mpis.setDeleteOnExit(true); - IllegalStateException x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); + IllegalStateException x = assertThrows(IllegalStateException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } @Test public void testRequestTooBigThrowsErrorOnGetParts() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -420,17 +405,16 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); //cause parsing - IllegalStateException x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); + IllegalStateException x = assertThrows(IllegalStateException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); //try again - x = assertThrows(IllegalStateException.class, () -> mpis.getParts()); + x = assertThrows(IllegalStateException.class, mpis::getParts); assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } @Test public void testFileTooBig() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -439,14 +423,13 @@ public class MultiPartFormInputStreamTest _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); } @Test public void testFileTooBigThrowsErrorOnGetParts() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -456,13 +439,13 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); // Caused parsing IllegalStateException x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); //test again after the parsing x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "stuff.txt should have been larger than maxFileSize"); assertThat(x.getMessage(), startsWith("Multipart Mime part")); } @@ -520,8 +503,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testLFOnlyRequest() - throws Exception + public void testLFOnlyRequest() throws Exception { String str = "--AaB03x\n" + "content-disposition: form-data; name=\"field1\"\n" + @@ -556,7 +538,6 @@ public class MultiPartFormInputStreamTest @Test public void testCROnlyRequest() - throws Exception { String str = "--AaB03x\r" + "content-disposition: form-data; name=\"field1\"\r" + @@ -576,14 +557,13 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "Improper EOL"); assertThat(x.getMessage(), containsString("Bad EOL")); } @Test public void testCRandLFMixRequest() - throws Exception { String str = "--AaB03x\r" + "content-disposition: form-data; name=\"field1\"\r" + @@ -604,7 +584,7 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "Improper EOL"); assertThat(x.getMessage(), containsString("Bad EOL")); } @@ -626,7 +606,7 @@ public class MultiPartFormInputStreamTest _tmpDir); mpis.setDeleteOnExit(true); IllegalStateException x = assertThrows(IllegalStateException.class, - () -> mpis.getParts(), + mpis::getParts, "Header Line Exceeded Max Length"); assertThat(x.getMessage(), containsString("Header Line Exceeded Max Length")); } @@ -724,8 +704,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testWriteFilesIfContentDispositionFilename() - throws Exception + public void testWriteFilesIfContentDispositionFilename() throws Exception { String s = "--AaB03x\r\n" + "content-disposition: form-data; name=\"field1\"; filename=\"frooble.txt\"\r\n" + @@ -823,8 +802,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testMultiSameNames() - throws Exception + public void testMultiSameNames() throws Exception { String sameNames = "--AaB03x\r\n" + "content-disposition: form-data; name=\"stuff\"; filename=\"stuff1.txt\"\r\n" + @@ -946,8 +924,7 @@ public class MultiPartFormInputStreamTest } @Test - public void testGeneratedForm() - throws Exception + public void testGeneratedForm() throws Exception { String contentType = "multipart/form-data, boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW"; String body = "Content-Type: multipart/form-data; boundary=WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW\r\n" + From 55748f12c23a55e845db4ddc487a2185120d79ac Mon Sep 17 00:00:00 2001 From: Lachlan Roberts Date: Tue, 18 Feb 2020 11:32:56 +1100 Subject: [PATCH 17/27] Issue #4581 - remove unnecessary javadoc on Override methods Signed-off-by: Lachlan Roberts --- .../apache/jsp/JettyJasperInitializer.java | 9 - .../jetty/apache/jsp/JettyTldPreScanned.java | 3 - .../jetty/jsp/TestJettyJspServlet.java | 3 - .../example/asyncrest/SerialRestServlet.java | 5 - .../annotations/AnnotationConfiguration.java | 9 - .../DeclareRolesAnnotationHandler.java | 3 - .../MultiPartConfigAnnotationHandler.java | 3 - .../ServletContainerInitializersStarter.java | 5 - .../ServletSecurityAnnotationHandler.java | 3 - .../annotations/WebFilterAnnotation.java | 3 - .../annotations/WebListenerAnnotation.java | 3 - .../annotations/WebServletAnnotation.java | 3 - .../eclipse/jetty/ant/AntWebAppContext.java | 3 - .../org/eclipse/jetty/ant/JettyStopTask.java | 3 - .../eclipse/jetty/ant/ServerProxyImpl.java | 6 - .../eclipse/jetty/client/ConnectionPool.java | 5 - .../PropertiesConfigurationManager.java | 3 - .../GCloudSessionDataStoreFactory.java | 3 - .../jetty/http/spi/JettyHttpsExchange.java | 3 - .../jetty/http/Http1FieldPreEncoder.java | 6 - .../java/org/eclipse/jetty/http/MetaData.java | 4 - .../http2/hpack/HpackFieldPreEncoder.java | 6 - .../InfinispanSessionDataStore.java | 3 - .../InfinispanSessionDataStoreFactory.java | 3 - .../eclipse/jetty/io/ByteArrayEndPoint.java | 12 -- .../jetty/jaas/spi/AbstractLoginModule.java | 4 - .../security/jaspi/JaspiAuthenticator.java | 3 - .../jetty/security/jaspi/JaspiTest.java | 6 - .../jetty/jndi/local/localContextRoot.java | 89 --------- .../jetty/maven/plugin/JettyDistroForker.java | 6 - .../MemcachedSessionDataMapFactory.java | 3 - .../annotations/AnnotationConfiguration.java | 3 - .../osgi/boot/AbstractContextProvider.java | 3 - .../osgi/boot/AbstractWebAppProvider.java | 3 - .../osgi/boot/BundleContextProvider.java | 6 - .../jetty/osgi/boot/BundleWebAppProvider.java | 12 -- .../osgi/boot/ServiceContextProvider.java | 9 - .../osgi/boot/ServiceWebAppProvider.java | 15 -- .../JettyServerServiceTracker.java | 9 - .../osgi/boot/utils/FakeURLClassLoader.java | 3 - .../boot/utils/ServerConnectorListener.java | 3 - .../main/java/com/acme/osgi/Activator.java | 3 - .../main/java/com/acme/osgi/Activator.java | 3 - .../plus/webapp/PlusDescriptorProcessor.java | 6 - .../QuickStartDescriptorProcessor.java | 6 - .../eclipse/jetty/quickstart/FooServlet.java | 3 - .../rewrite/handler/CookiePatternRule.java | 4 - .../jetty/rewrite/handler/PatternRule.java | 3 - .../rewrite/handler/ResponsePatternRule.java | 4 - .../jetty/rewrite/handler/RewriteHandler.java | 3 - .../rewrite/handler/RewriteRegexRule.java | 3 - .../jetty/security/AbstractLoginService.java | 15 -- .../security/ConstraintSecurityHandler.java | 15 -- .../jetty/security/HashLoginService.java | 6 - .../jetty/security/JDBCLoginService.java | 3 - .../jetty/security/SecurityHandler.java | 3 - .../authentication/BasicAuthenticator.java | 6 - .../DeferredAuthentication.java | 9 - .../authentication/FormAuthenticator.java | 3 - .../jetty/security/ConstraintTest.java | 3 - .../jetty/security/TestLoginService.java | 6 - .../org/eclipse/jetty/server/Request.java | 161 +-------------- .../java/org/eclipse/jetty/server/Server.java | 15 -- .../server/ServletRequestHttpWrapper.java | 21 -- .../server/ServletResponseHttpWrapper.java | 12 -- .../jetty/server/handler/AbstractHandler.java | 6 - .../handler/BufferedResponseHandler.java | 3 - .../jetty/server/handler/ContextHandler.java | 71 ------- .../jetty/server/handler/DebugHandler.java | 9 - .../jetty/server/handler/DefaultHandler.java | 3 - .../jetty/server/handler/HandlerList.java | 3 - .../jetty/server/handler/HotSwapHandler.java | 9 - .../server/handler/RequestLogHandler.java | 3 - .../jetty/server/handler/ResourceHandler.java | 3 - .../jetty/server/handler/ScopedHandler.java | 3 - .../server/session/AbstractSessionCache.java | 21 -- .../session/CachingSessionDataStore.java | 24 --- .../CachingSessionDataStoreFactory.java | 3 - .../jetty/server/session/DatabaseAdaptor.java | 3 - .../session/DefaultSessionIdManager.java | 12 -- .../session/FileSessionDataStoreFactory.java | 3 - .../jetty/server/session/HouseKeeper.java | 9 - .../session/JDBCSessionDataStoreFactory.java | 3 - .../session/NullSessionDataStoreFactory.java | 3 - .../eclipse/jetty/server/session/Session.java | 41 ---- .../jetty/server/session/SessionHandler.java | 15 -- .../jetty/server/ConnectorCloseTestBase.java | 3 - .../eclipse/jetty/servlet/DefaultServlet.java | 6 - .../eclipse/jetty/servlet/NoJspServlet.java | 3 - .../jetty/servlet/ServletContextHandler.java | 56 ------ .../eclipse/jetty/servlet/ServletHolder.java | 6 - .../org/eclipse/jetty/servlet/Source.java | 3 - .../java/org/eclipse/jetty/util/HostMap.java | 6 - .../main/java/org/eclipse/jetty/util/IO.java | 3 - .../org/eclipse/jetty/util/PathWatcher.java | 15 -- .../org/eclipse/jetty/util/UrlEncoded.java | 3 - .../jetty/util/log/JettyAwareLogger.java | 183 ------------------ .../util/preventers/AWTLeakPreventer.java | 3 - .../util/preventers/DOMLeakPreventer.java | 3 - .../preventers/GCThreadLeakPreventer.java | 3 - .../util/preventers/Java2DLeakPreventer.java | 3 - .../util/preventers/LDAPLeakPreventer.java | 3 - .../LoginConfigurationLeakPreventer.java | 3 - .../SecurityProviderLeakPreventer.java | 3 - .../eclipse/jetty/webapp/WebAppContext.java | 6 - .../jetty/webapp/WebInfConfiguration.java | 3 - .../eclipse/jetty/webapp/OrderingTest.java | 39 ---- .../distribution/DistributionTester.java | 3 - .../eclipse/jetty/test/DigestPostTest.java | 6 - .../jetty/test/jsp/FakeJspServlet.java | 3 - .../session/ClusteredOrphanedSessionTest.java | 3 - .../session/FileSessionDataStoreTest.java | 3 - .../session/ClusteredOrphanedSessionTest.java | 3 - .../ClusteredSessionScavengingTest.java | 3 - .../session/GCloudSessionDataStoreTest.java | 3 - .../session/GCloudSessionTestSupport.java | 3 - .../session/InvalidationSessionTest.java | 3 - .../session/ClusteredOrphanedSessionTest.java | 3 - .../ClusteredSessionScavengingTest.java | 3 - .../session/ClusteredOrphanedSessionTest.java | 3 - .../ClusteredSessionScavengingTest.java | 3 - ...emoteClusteredInvalidationSessionTest.java | 3 - .../RemoteClusteredSessionScavengingTest.java | 3 - .../ClusteredInvalidationSessionTest.java | 3 - .../session/ClusteredOrphanedSessionTest.java | 3 - .../ClusteredSessionScavengingTest.java | 3 - .../session/SessionTableSchemaTest.java | 3 - .../session/WebAppObjectInSessionTest.java | 3 - .../sessions/MemcachedTestHelper.java | 3 - .../ClusteredInvalidateSessionTest.java | 3 - .../mongodb/ClusteredOrphanedSessionTest.java | 3 - .../ClusteredSessionScavengingTest.java | 3 - .../session/TestSessionDataStoreFactory.java | 3 - .../session/DeleteUnloadableSessionTest.java | 3 - .../server/session/DirtyAttributeTest.java | 18 -- .../session/SessionEvictionFailureTest.java | 3 - .../src/main/java/com/acme/TestFilter.java | 9 - .../java/org/eclipse/jetty/TestServer.java | 3 - .../main/java/com/acme/MockDataSource.java | 18 -- .../src/main/java/com/acme/MockTransport.java | 3 - .../java/com/acme/MockUserTransaction.java | 18 -- .../com/acme/initializer/FooInitializer.java | 12 -- .../tests/webapp/HttpMethodsServlet.java | 20 -- 143 files changed, 1 insertion(+), 1398 deletions(-) diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java index 096f5f4a2e6..9ab013880f5 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyJasperInitializer.java @@ -54,27 +54,18 @@ public class JettyJasperInitializer extends JasperInitializer super(context, namespaceAware, validation, blockExternal); } - /** - * @see org.apache.jasper.servlet.TldScanner#scan() - */ @Override public void scan() throws IOException, SAXException { return; //do nothing } - /** - * @see org.apache.jasper.servlet.TldScanner#getListeners() - */ @Override public List getListeners() { return Collections.emptyList(); } - /** - * @see org.apache.jasper.servlet.TldScanner#scanJars() - */ @Override public void scanJars() { diff --git a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java index fd5de945368..1283892c243 100644 --- a/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java +++ b/apache-jsp/src/main/java/org/eclipse/jetty/apache/jsp/JettyTldPreScanned.java @@ -48,9 +48,6 @@ public class JettyTldPreScanned extends TldPreScanned _jettyPreScannedURLs = preScannedTlds; } - /** - * @see org.apache.jasper.servlet.TldPreScanned#scanJars() - */ @Override public void scanJars() { diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java index 397aea026f7..e53da63c82c 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java @@ -62,9 +62,6 @@ public class TestJettyJspServlet super(); } - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java index 8abf15abf12..e7c8bf01590 100644 --- a/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java +++ b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java @@ -28,7 +28,6 @@ import java.util.LinkedList; import java.util.Map; import java.util.Queue; import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -94,10 +93,6 @@ public class SerialRestServlet extends AbstractRestServlet out.close(); } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java index 831a15f6677..199b313fa14 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationConfiguration.java @@ -332,9 +332,6 @@ public class AnnotationConfiguration extends AbstractConfiguration _discoverableAnnotationHandlers.add(handler); } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#configure(org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void configure(WebAppContext context) throws Exception { @@ -371,9 +368,6 @@ public class AnnotationConfiguration extends AbstractConfiguration } } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#postConfigure(org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void postConfigure(WebAppContext context) throws Exception { @@ -563,9 +557,6 @@ public class AnnotationConfiguration extends AbstractConfiguration return Integer.getInteger(MAX_SCAN_WAIT, DEFAULT_MAX_SCAN_WAIT).intValue(); } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#cloneConfigure(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void cloneConfigure(WebAppContext template, WebAppContext context) throws Exception { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java index be7c373fb3c..46c6cf4b491 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/DeclareRolesAnnotationHandler.java @@ -43,9 +43,6 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat _context = context; } - /** - * @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class) - */ @Override public void doHandle(Class clazz) { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java index 58f582c1db9..105e9d760d1 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/MultiPartConfigAnnotationHandler.java @@ -42,9 +42,6 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno _context = context; } - /** - * @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class) - */ @Override public void doHandle(Class clazz) { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletContainerInitializersStarter.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletContainerInitializersStarter.java index 805b9ce36c1..e92828673b4 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletContainerInitializersStarter.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletContainerInitializersStarter.java @@ -43,11 +43,6 @@ public class ServletContainerInitializersStarter extends AbstractLifeCycle imple _context = context; } - /** - * Call the doStart method of the ServletContainerInitializers - * - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override public void doStart() { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletSecurityAnnotationHandler.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletSecurityAnnotationHandler.java index 34474310832..51340b98c7a 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletSecurityAnnotationHandler.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/ServletSecurityAnnotationHandler.java @@ -65,9 +65,6 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno _context = wac; } - /** - * @see org.eclipse.jetty.annotations.AnnotationIntrospector.IntrospectableAnnotationHandler#handle(java.lang.Class) - */ @Override public void doHandle(Class clazz) { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java index f609e026925..07f3919c4f8 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebFilterAnnotation.java @@ -54,9 +54,6 @@ public class WebFilterAnnotation extends DiscoveredAnnotation super(context, className, resource); } - /** - * @see DiscoveredAnnotation#apply() - */ @Override public void apply() { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java index 104dfba74da..50613c38870 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebListenerAnnotation.java @@ -54,9 +54,6 @@ public class WebListenerAnnotation extends DiscoveredAnnotation super(context, className, resource); } - /** - * @see DiscoveredAnnotation#apply() - */ @Override public void apply() { diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java index e7a7c7f641f..84986bf6e9f 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/WebServletAnnotation.java @@ -57,9 +57,6 @@ public class WebServletAnnotation extends DiscoveredAnnotation super(context, className, resource); } - /** - * @see DiscoveredAnnotation#apply() - */ @Override public void apply() { diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java index ba71267a162..56b200b599c 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/AntWebAppContext.java @@ -563,9 +563,6 @@ public class AntWebAppContext extends WebAppContext } } - /** - * - */ @Override public void doStart() { diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java index 6ee1cee7500..0a71fc67611 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/JettyStopTask.java @@ -49,9 +49,6 @@ public class JettyStopTask extends Task TaskLog.setTask(this); } - /** - * @see org.apache.tools.ant.Task#execute() - */ @Override public void execute() throws BuildException { diff --git a/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java b/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java index feb95456da1..16460fe7c18 100644 --- a/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java +++ b/jetty-ant/src/main/java/org/eclipse/jetty/ant/ServerProxyImpl.java @@ -254,9 +254,6 @@ public class ServerProxyImpl implements ServerProxy this.tempDirectory = tempDirectory; } - /** - * @see org.eclipse.jetty.ant.utils.ServerProxy#start() - */ @Override public void start() { @@ -299,9 +296,6 @@ public class ServerProxyImpl implements ServerProxy } } - /** - * @see org.eclipse.jetty.ant.utils.ServerProxy#getProxiedObject() - */ @Override public Object getProxiedObject() { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/ConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/ConnectionPool.java index 78e65014c72..10108dd819f 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/ConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/ConnectionPool.java @@ -70,11 +70,6 @@ public interface ConnectionPool extends Closeable */ boolean remove(Connection connection); - /** - * Closes this ConnectionPool. - * - * @see #isClosed() - */ @Override void close(); diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java index 317757400ac..14424b416db 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/PropertiesConfigurationManager.java @@ -81,9 +81,6 @@ public class PropertiesConfigurationManager implements ConfigurationManager, Dum _map.put(name, value); } - /** - * @see org.eclipse.jetty.deploy.ConfigurationManager#getProperties() - */ @Override public Map getProperties() { diff --git a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java index 2a6b767302c..10874cb76e8 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java +++ b/jetty-gcloud/jetty-gcloud-session-manager/src/main/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreFactory.java @@ -78,9 +78,6 @@ public class GCloudSessionDataStoreFactory extends AbstractSessionDataStoreFacto _namespace = namespace; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java index f275db38013..99426f059da 100644 --- a/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java +++ b/jetty-http-spi/src/main/java/org/eclipse/jetty/http/spi/JettyHttpsExchange.java @@ -171,9 +171,6 @@ public class JettyHttpsExchange extends HttpsExchange implements JettyExchange return _delegate.toString(); } - /** - * @see com.sun.net.httpserver.HttpsExchange#getSSLSession() - */ @Override public SSLSession getSSLSession() { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java b/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java index 85600a80c09..9308fd3450d 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/Http1FieldPreEncoder.java @@ -28,18 +28,12 @@ import static java.nio.charset.StandardCharsets.ISO_8859_1; public class Http1FieldPreEncoder implements HttpFieldPreEncoder { - /** - * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getHttpVersion() - */ @Override public HttpVersion getHttpVersion() { return HttpVersion.HTTP_1_0; } - /** - * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getEncodedField(org.eclipse.jetty.http.HttpHeader, java.lang.String, java.lang.String) - */ @Override public byte[] getEncodedField(HttpHeader header, String headerString, String value) { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java index 3ec17513c96..491cd123b1c 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MetaData.java @@ -109,10 +109,6 @@ public class MetaData implements Iterable return _contentLength; } - /** - * @return an iterator over the HTTP fields - * @see #getFields() - */ @Override public Iterator iterator() { diff --git a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java index e1c33e1ff73..040c61c221e 100644 --- a/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java +++ b/jetty-http2/http2-hpack/src/main/java/org/eclipse/jetty/http2/hpack/HpackFieldPreEncoder.java @@ -31,18 +31,12 @@ import org.eclipse.jetty.util.BufferUtil; public class HpackFieldPreEncoder implements HttpFieldPreEncoder { - /** - * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getHttpVersion() - */ @Override public HttpVersion getHttpVersion() { return HttpVersion.HTTP_2; } - /** - * @see org.eclipse.jetty.http.HttpFieldPreEncoder#getEncodedField(org.eclipse.jetty.http.HttpHeader, java.lang.String, java.lang.String) - */ @Override public byte[] getEncodedField(HttpHeader header, String name, String value) { diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java index bd8abf5473f..0598f614bf5 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStore.java @@ -82,9 +82,6 @@ public class InfinispanSessionDataStore extends AbstractSessionDataStore _queryManager = queryManager; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#load(String) - */ @Override protected void doStart() throws Exception { diff --git a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java index f2c86b6691d..55c92e42b91 100644 --- a/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java +++ b/jetty-infinispan/infinispan-common/src/main/java/org/eclipse/jetty/session/infinispan/InfinispanSessionDataStoreFactory.java @@ -49,9 +49,6 @@ public class InfinispanSessionDataStoreFactory extends AbstractSessionDataStoreF _infinispanIdleTimeoutSec = infinispanIdleTimeoutSec; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java index 79102ed185c..50cdf335de5 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java @@ -355,9 +355,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint return getOutput().position() > 0; } - /* - * @see org.eclipse.io.EndPoint#fill(org.eclipse.io.Buffer) - */ @Override public int fill(ByteBuffer buffer) throws IOException { @@ -400,9 +397,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint return filled; } - /* - * @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer, org.eclipse.io.Buffer, org.eclipse.io.Buffer) - */ @Override public boolean flush(ByteBuffer... buffers) throws IOException { @@ -450,9 +444,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint return flushed; } - /** - * - */ @Override public void reset() { @@ -465,9 +456,6 @@ public class ByteArrayEndPoint extends AbstractEndPoint super.reset(); } - /* - * @see org.eclipse.io.EndPoint#getConnection() - */ @Override public Object getTransport() { diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java index 3a99c8427e6..2bbb253b7f3 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/AbstractLoginModule.java @@ -179,10 +179,6 @@ public abstract class AbstractLoginModule implements LoginModule this.commitState = commitState; } - /** - * @throws LoginException if unable to abort - * @see javax.security.auth.spi.LoginModule#abort() - */ @Override public boolean abort() throws LoginException { diff --git a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java index 9f447819deb..9a110eda17f 100644 --- a/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java +++ b/jetty-jaspi/src/main/java/org/eclipse/jetty/security/jaspi/JaspiAuthenticator.java @@ -94,9 +94,6 @@ public class JaspiAuthenticator extends LoginAuthenticator return "JASPI"; } - /** - * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#login(java.lang.String, java.lang.Object, javax.servlet.ServletRequest) - */ @Override public UserIdentity login(String username, Object password, ServletRequest request) { diff --git a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java index 32755d01453..d8f34c2ac18 100644 --- a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java +++ b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java @@ -69,18 +69,12 @@ public class JaspiTest _roles.put(username, roles); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadRoleInfo(org.eclipse.jetty.security.AbstractLoginService.UserPrincipal) - */ @Override protected String[] loadRoleInfo(UserPrincipal user) { return _roles.get(user.getName()); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadUserInfo(java.lang.String) - */ @Override protected UserPrincipal loadUserInfo(String username) { diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java index 6f774709404..364f3dafc67 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/local/localContextRoot.java @@ -98,44 +98,29 @@ public class localContextRoot implements Context _env = new Hashtable(env); } - /** - * @see javax.naming.Context#close() - */ @Override public void close() throws NamingException { } - /** - * @see javax.naming.Context#getNameInNamespace() - */ @Override public String getNameInNamespace() throws NamingException { return ""; } - /** - * @see javax.naming.Context#destroySubcontext(javax.naming.Name) - */ @Override public void destroySubcontext(Name name) throws NamingException { __root.destroySubcontext(getSuffix(name)); } - /** - * @see javax.naming.Context#destroySubcontext(java.lang.String) - */ @Override public void destroySubcontext(String name) throws NamingException { destroySubcontext(__root.getNameParser("").parse(getSuffix(name))); } - /** - * @see javax.naming.Context#getEnvironment() - */ @Override public Hashtable getEnvironment() throws NamingException { @@ -186,9 +171,6 @@ public class localContextRoot implements Context return (Context)ctx; } - /** - * @see javax.naming.Context#unbind(javax.naming.Name) - */ @Override public void unbind(Name name) throws NamingException { @@ -219,27 +201,18 @@ public class localContextRoot implements Context } } - /** - * @see javax.naming.Context#unbind(java.lang.String) - */ @Override public void unbind(String name) throws NamingException { unbind(__root.getNameParser("").parse(getSuffix(name))); } - /** - * @see javax.naming.Context#lookupLink(java.lang.String) - */ @Override public Object lookupLink(String name) throws NamingException { return lookupLink(__root.getNameParser("").parse(getSuffix(name))); } - /** - * @see javax.naming.Context#lookupLink(javax.naming.Name) - */ @Override public Object lookupLink(Name name) throws NamingException { @@ -292,18 +265,12 @@ public class localContextRoot implements Context return getContext(cname).lookup(cname.getSuffix(1)); } - /** - * @see javax.naming.Context#removeFromEnvironment(java.lang.String) - */ @Override public Object removeFromEnvironment(String propName) throws NamingException { return _env.remove(propName); } - /** - * @see javax.naming.Context#lookup(javax.naming.Name) - */ @Override public Object lookup(Name name) throws NamingException { @@ -370,27 +337,18 @@ public class localContextRoot implements Context return getContext(cname).lookup(cname.getSuffix(1)); } - /** - * @see javax.naming.Context#lookup(java.lang.String) - */ @Override public Object lookup(String name) throws NamingException { return lookup(__root.getNameParser("").parse(getSuffix(name))); } - /** - * @see javax.naming.Context#bind(java.lang.String, java.lang.Object) - */ @Override public void bind(String name, Object obj) throws NamingException { bind(__root.getNameParser("").parse(getSuffix(name)), obj); } - /** - * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object) - */ @Override public void bind(Name name, Object obj) throws NamingException { @@ -428,9 +386,6 @@ public class localContextRoot implements Context } } - /** - * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object) - */ @Override public void rebind(Name name, Object obj) throws NamingException { @@ -468,36 +423,24 @@ public class localContextRoot implements Context } } - /** - * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object) - */ @Override public void rebind(String name, Object obj) throws NamingException { rebind(__root.getNameParser("").parse(getSuffix(name)), obj); } - /** - * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name) - */ @Override public void rename(Name oldName, Name newName) throws NamingException { throw new OperationNotSupportedException(); } - /** - * @see javax.naming.Context#rename(java.lang.String, java.lang.String) - */ @Override public void rename(String oldName, String newName) throws NamingException { throw new OperationNotSupportedException(); } - /** - * @see javax.naming.Context#createSubcontext(java.lang.String) - */ @Override public Context createSubcontext(String name) throws NamingException { @@ -512,9 +455,6 @@ public class localContextRoot implements Context return createSubcontext(__root.getNameParser("").parse(name)); } - /** - * @see javax.naming.Context#createSubcontext(javax.naming.Name) - */ @Override public Context createSubcontext(Name name) throws NamingException { @@ -557,64 +497,42 @@ public class localContextRoot implements Context return getContext(cname).createSubcontext(cname.getSuffix(1)); } - /** - * @see javax.naming.Context#getNameParser(java.lang.String) - */ @Override public NameParser getNameParser(String name) throws NamingException { return __root.getNameParser(name); } - /** - * @see javax.naming.Context#getNameParser(javax.naming.Name) - */ @Override public NameParser getNameParser(Name name) throws NamingException { return __root.getNameParser(name); } - /** - * @see javax.naming.Context#list(java.lang.String) - */ @Override public NamingEnumeration list(String name) throws NamingException { return __root.list(name); } - /** - * @see javax.naming.Context#list(javax.naming.Name) - */ @Override public NamingEnumeration list(Name name) throws NamingException { return __root.list(name); } - /** - * @see javax.naming.Context#listBindings(javax.naming.Name) - */ @Override public NamingEnumeration listBindings(Name name) throws NamingException { return __root.listBindings(name); } - /** - * @see javax.naming.Context#listBindings(java.lang.String) - */ @Override public NamingEnumeration listBindings(String name) throws NamingException { return __root.listBindings(name); } - /** - * @see javax.naming.Context#addToEnvironment(java.lang.String, - * java.lang.Object) - */ @Override public Object addToEnvironment(String propName, Object propVal) throws NamingException @@ -622,9 +540,6 @@ public class localContextRoot implements Context return _env.put(propName, propVal); } - /** - * @see javax.naming.Context#composeName(java.lang.String, java.lang.String) - */ @Override public String composeName(String name, String prefix) throws NamingException @@ -632,10 +547,6 @@ public class localContextRoot implements Context return __root.composeName(name, prefix); } - /** - * @see javax.naming.Context#composeName(javax.naming.Name, - * javax.naming.Name) - */ @Override public Name composeName(Name name, Name prefix) throws NamingException { diff --git a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java index 48178c8450d..641662cc9b4 100644 --- a/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java +++ b/jetty-maven-plugin/src/main/java/org/eclipse/jetty/maven/plugin/JettyDistroForker.java @@ -165,9 +165,6 @@ public class JettyDistroForker extends AbstractForker this.baseDir = baseDir; } - /** - * @see org.eclipse.jetty.maven.plugin.AbstractForker#createCommand() - */ @Override protected ProcessBuilder createCommand() { @@ -324,9 +321,6 @@ public class JettyDistroForker extends AbstractForker return FileVisitResult.CONTINUE; } - /** - * @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, java.nio.file.attribute.BasicFileAttributes) - */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { diff --git a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java index c41664c8186..e04ca05a327 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java +++ b/jetty-memcached/jetty-memcached-sessions/src/main/java/org/eclipse/jetty/memcached/session/MemcachedSessionDataMapFactory.java @@ -83,9 +83,6 @@ public class MemcachedSessionDataMapFactory implements SessionDataMapFactory _heartbeats = heartbeats; } - /** - * @see org.eclipse.jetty.server.session.SessionDataMapFactory#getSessionDataMap() - */ @Override public SessionDataMap getSessionDataMap() { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java index 8f86d957652..ba4f499fa48 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/annotations/AnnotationConfiguration.java @@ -194,9 +194,6 @@ public class AnnotationConfiguration extends org.eclipse.jetty.annotations.Annot parseBundle(context, parser, webbundle, webbundle); } - /** - * @see org.eclipse.jetty.annotations.AnnotationConfiguration#parseWebInfClasses(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.annotations.AnnotationParser) - */ @Override public void parseWebInfClasses(WebAppContext context, org.eclipse.jetty.annotations.AnnotationParser parser) throws Exception diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java index a6c2b091209..9372f9b58fc 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractContextProvider.java @@ -208,9 +208,6 @@ public abstract class AbstractContextProvider extends AbstractLifeCycle implemen return _serverWrapper; } - /** - * @see org.eclipse.jetty.deploy.AppProvider#createContextHandler(org.eclipse.jetty.deploy.App) - */ @Override public ContextHandler createContextHandler(App app) throws Exception { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java index d3aa1caace4..6f1b71fdbdd 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/AbstractWebAppProvider.java @@ -530,9 +530,6 @@ public abstract class AbstractWebAppProvider extends AbstractLifeCycle implement return _deploymentManager; } - /** - * @see org.eclipse.jetty.deploy.AppProvider#setDeploymentManager(org.eclipse.jetty.deploy.DeploymentManager) - */ @Override public void setDeploymentManager(DeploymentManager deploymentManager) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java index e8252928720..8e5a0ff6268 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleContextProvider.java @@ -64,9 +64,6 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu _managedServerName = managedServerName; } - /** - * @see org.osgi.util.tracker.BundleTracker#addingBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent) - */ @Override public Object addingBundle(Bundle bundle, BundleEvent event) { @@ -87,9 +84,6 @@ public class BundleContextProvider extends AbstractContextProvider implements Bu return null; } - /** - * @see org.osgi.util.tracker.BundleTracker#removedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object) - */ @Override public void removedBundle(Bundle bundle, BundleEvent event, Object object) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java index 9168bcebac7..466b9f9c6a2 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/BundleWebAppProvider.java @@ -64,9 +64,6 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund _managedServerName = managedServerName; } - /** - * @see org.osgi.util.tracker.BundleTracker#addingBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent) - */ @Override public Object addingBundle(Bundle bundle, BundleEvent event) { @@ -87,9 +84,6 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund return null; } - /** - * @see org.osgi.util.tracker.BundleTracker#removedBundle(org.osgi.framework.Bundle, org.osgi.framework.BundleEvent, java.lang.Object) - */ @Override public void removedBundle(Bundle bundle, BundleEvent event, Object object) { @@ -109,9 +103,6 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund super(wrapper); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -124,9 +115,6 @@ public class BundleWebAppProvider extends AbstractWebAppProvider implements Bund super.doStart(); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java index 563b0e4dcfb..45b2fe64542 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceContextProvider.java @@ -66,9 +66,6 @@ public class ServiceContextProvider extends AbstractContextProvider implements S super(bundleContext, filter, null); } - /** - * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) - */ @Override public Object addingService(ServiceReference reference) { @@ -77,9 +74,6 @@ public class ServiceContextProvider extends AbstractContextProvider implements S return h; } - /** - * @see org.osgi.util.tracker.ServiceTracker#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void modifiedService(ServiceReference reference, Object service) { @@ -87,9 +81,6 @@ public class ServiceContextProvider extends AbstractContextProvider implements S addingService(reference); } - /** - * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void removedService(ServiceReference reference, Object service) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java index 94f7da7f12e..3437facef48 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/ServiceWebAppProvider.java @@ -72,9 +72,6 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser super(bundleContext, filter, null); } - /** - * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) - */ @Override public Object addingService(ServiceReference reference) { @@ -83,9 +80,6 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser return wac; } - /** - * @see org.osgi.util.tracker.ServiceTracker#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void modifiedService(ServiceReference reference, Object service) { @@ -93,9 +87,6 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser addingService(reference); } - /** - * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void removedService(ServiceReference reference, Object service) { @@ -229,9 +220,6 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser return false; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -251,9 +239,6 @@ public class ServiceWebAppProvider extends AbstractWebAppProvider implements Ser super.doStart(); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java index 902c4b8523e..de5a0438596 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/JettyServerServiceTracker.java @@ -39,9 +39,6 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer { private static Logger LOG = Log.getLogger(JettyServerServiceTracker.class.getName()); - /** - * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference) - */ @Override public Object addingService(ServiceReference sr) { @@ -73,9 +70,6 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer } } - /** - * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void modifiedService(ServiceReference reference, Object service) { @@ -83,9 +77,6 @@ public class JettyServerServiceTracker implements ServiceTrackerCustomizer addingService(reference); } - /** - * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference, java.lang.Object) - */ @Override public void removedService(ServiceReference reference, Object service) { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java index 84f5b51f651..1c0938848f4 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/FakeURLClassLoader.java @@ -52,9 +52,6 @@ public class FakeURLClassLoader extends URLClassLoader return _jars; } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java index 5d94979e85e..2edfc3bbeeb 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/ServerConnectorListener.java @@ -38,9 +38,6 @@ public class ServerConnectorListener extends AbstractLifeCycleListener private Path _filePath; private String _sysPropertyName; - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) - */ @Override public void lifeCycleStarted(LifeCycle event) { diff --git a/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java b/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java index 62bba903133..ab85f2b9de1 100644 --- a/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java +++ b/jetty-osgi/test-jetty-osgi-server/src/main/java/com/acme/osgi/Activator.java @@ -49,9 +49,6 @@ public class Activator implements BundleActivator server.getConnectors()[0].addEventListener(new AbstractLifeCycleListener() { - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener#lifeCycleStarted(org.eclipse.jetty.util.component.LifeCycle) - */ @Override public void lifeCycleStarted(LifeCycle event) { diff --git a/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java b/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java index 258a25bddcb..0184d027048 100644 --- a/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java +++ b/jetty-osgi/test-jetty-osgi-webapp/src/main/java/com/acme/osgi/Activator.java @@ -45,9 +45,6 @@ public class Activator implements BundleActivator public static class TestServlet extends HttpServlet { - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/webapp/PlusDescriptorProcessor.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/webapp/PlusDescriptorProcessor.java index 213f94f7401..0be8e069957 100644 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/webapp/PlusDescriptorProcessor.java +++ b/jetty-plus/src/main/java/org/eclipse/jetty/plus/webapp/PlusDescriptorProcessor.java @@ -69,9 +69,6 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor } } - /** - * @see org.eclipse.jetty.webapp.IterativeDescriptorProcessor#start(WebAppContext, org.eclipse.jetty.webapp.Descriptor) - */ @Override public void start(WebAppContext context, Descriptor descriptor) { @@ -98,9 +95,6 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor } } - /** - * {@inheritDoc} - */ @Override public void end(WebAppContext context, Descriptor descriptor) { diff --git a/jetty-quickstart/src/main/java/org/eclipse/jetty/quickstart/QuickStartDescriptorProcessor.java b/jetty-quickstart/src/main/java/org/eclipse/jetty/quickstart/QuickStartDescriptorProcessor.java index 4f5a944f382..386c0258187 100644 --- a/jetty-quickstart/src/main/java/org/eclipse/jetty/quickstart/QuickStartDescriptorProcessor.java +++ b/jetty-quickstart/src/main/java/org/eclipse/jetty/quickstart/QuickStartDescriptorProcessor.java @@ -65,18 +65,12 @@ public class QuickStartDescriptorProcessor extends IterativeDescriptorProcessor } } - /** - * @see org.eclipse.jetty.webapp.IterativeDescriptorProcessor#start(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.webapp.Descriptor) - */ @Override public void start(WebAppContext context, Descriptor descriptor) { _originAttributeName = context.getInitParameter(QuickStartGeneratorConfiguration.ORIGIN); } - /** - * @see org.eclipse.jetty.webapp.IterativeDescriptorProcessor#end(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.webapp.Descriptor) - */ @Override public void end(WebAppContext context, Descriptor descriptor) { diff --git a/jetty-quickstart/src/test/java/org/eclipse/jetty/quickstart/FooServlet.java b/jetty-quickstart/src/test/java/org/eclipse/jetty/quickstart/FooServlet.java index b2305b58ce5..36a0bf9ea51 100644 --- a/jetty-quickstart/src/test/java/org/eclipse/jetty/quickstart/FooServlet.java +++ b/jetty-quickstart/src/test/java/org/eclipse/jetty/quickstart/FooServlet.java @@ -27,9 +27,6 @@ import javax.servlet.http.HttpServletResponse; public class FooServlet extends HttpServlet { - /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/CookiePatternRule.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/CookiePatternRule.java index 721c3a1ba13..9290dd3811e 100644 --- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/CookiePatternRule.java +++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/CookiePatternRule.java @@ -70,10 +70,6 @@ public class CookiePatternRule extends PatternRule _value = value; } - /* - * (non-Javadoc) - * @see org.eclipse.jetty.server.server.handler.rules.RuleBase#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java index e32d6d5c738..11afc47b21d 100644 --- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java +++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/PatternRule.java @@ -57,9 +57,6 @@ public abstract class PatternRule extends Rule _pattern = pattern; } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.server.handler.rules.RuleBase#matchAndApply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.java index a127afe0507..01d866148c2 100644 --- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.java +++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.java @@ -68,10 +68,6 @@ public class ResponsePatternRule extends PatternRule _message = message; } - /* - * (non-Javadoc) - * @see org.eclipse.jetty.server.server.handler.rules.RuleBase#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteHandler.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteHandler.java index 9d87ccc35a0..81db59e9457 100644 --- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteHandler.java +++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteHandler.java @@ -293,9 +293,6 @@ public class RewriteHandler extends HandlerWrapper _dispatchTypes = EnumSet.copyOf(Arrays.asList(types)); } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java index a1ead267848..fdfe7587216 100644 --- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java +++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java @@ -75,9 +75,6 @@ public class RewriteRegexRule extends RegexRule implements Rule.ApplyURI } } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.handler.rules.RegexRule#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.regex.Matcher) - */ @Override public String apply(String target, HttpServletRequest request, HttpServletResponse response, Matcher matcher) throws IOException { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/AbstractLoginService.java b/jetty-security/src/main/java/org/eclipse/jetty/security/AbstractLoginService.java index c163635187b..a0471ea722f 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/AbstractLoginService.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/AbstractLoginService.java @@ -107,9 +107,6 @@ public abstract class AbstractLoginService extends ContainerLifeCycle implements addBean(_identityService); } - /** - * @see org.eclipse.jetty.security.LoginService#getName() - */ @Override public String getName() { @@ -148,9 +145,6 @@ public abstract class AbstractLoginService extends ContainerLifeCycle implements return String.format("%s@%x[%s]", this.getClass().getSimpleName(), hashCode(), _name); } - /** - * @see org.eclipse.jetty.security.LoginService#login(java.lang.String, java.lang.Object, javax.servlet.ServletRequest) - */ @Override public UserIdentity login(String username, Object credentials, ServletRequest request) { @@ -178,9 +172,6 @@ public abstract class AbstractLoginService extends ContainerLifeCycle implements return null; } - /** - * @see org.eclipse.jetty.security.LoginService#validate(org.eclipse.jetty.server.UserIdentity) - */ @Override public boolean validate(UserIdentity user) { @@ -200,18 +191,12 @@ public abstract class AbstractLoginService extends ContainerLifeCycle implements throw new IllegalStateException("UserPrincipal not KnownUser"); //can't validate } - /** - * @see org.eclipse.jetty.security.LoginService#getIdentityService() - */ @Override public IdentityService getIdentityService() { return _identityService; } - /** - * @see org.eclipse.jetty.security.LoginService#logout(org.eclipse.jetty.server.UserIdentity) - */ @Override public void logout(UserIdentity user) { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java index 764e017d821..68851c767da 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java @@ -352,9 +352,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr _roles.addAll(roles); } - /** - * @see org.eclipse.jetty.security.ConstraintAware#addConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) - */ @Override public void addConstraintMapping(ConstraintMapping mapping) { @@ -377,9 +374,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr } } - /** - * @see org.eclipse.jetty.security.ConstraintAware#addRole(java.lang.String) - */ @Override public void addRole(String role) { @@ -399,9 +393,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr } } - /** - * @see org.eclipse.jetty.security.SecurityHandler#doStart() - */ @Override protected void doStart() throws Exception { @@ -677,9 +668,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr return constraintInfo != null && ((RoleInfo)constraintInfo).isChecked(); } - /** - * @see org.eclipse.jetty.security.SecurityHandler#checkWebResourcePermissions(java.lang.String, org.eclipse.jetty.server.Request, org.eclipse.jetty.server.Response, java.lang.Object, org.eclipse.jetty.server.UserIdentity) - */ @Override protected boolean checkWebResourcePermissions(String pathInContext, Request request, Response response, Object constraintInfo, UserIdentity userIdentity) throws IOException @@ -735,9 +723,6 @@ public class ConstraintSecurityHandler extends SecurityHandler implements Constr DumpableCollection.from("constraints", _constraintMappings)); } - /** - * @see org.eclipse.jetty.security.ConstraintAware#setDenyUncoveredHttpMethods(boolean) - */ @Override public void setDenyUncoveredHttpMethods(boolean deny) { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/HashLoginService.java b/jetty-security/src/main/java/org/eclipse/jetty/security/HashLoginService.java index 81062e59df4..0730a9bc324 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/HashLoginService.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/HashLoginService.java @@ -150,9 +150,6 @@ public class HashLoginService extends AbstractLoginService return null; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -191,9 +188,6 @@ public class HashLoginService extends AbstractLoginService return _userStoreAutoCreate; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java b/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java index 9da49113e5f..ec49dc2f716 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/JDBCLoginService.java @@ -262,9 +262,6 @@ public class JDBCLoginService extends AbstractLoginService return null; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java index b7e112ed98c..e2a907b53ef 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/SecurityHandler.java @@ -444,9 +444,6 @@ public abstract class SecurityHandler extends HandlerWrapper implements Authenti } } - /** - * @see org.eclipse.jetty.security.Authenticator.AuthConfiguration#isSessionRenewedOnAuthentication() - */ @Override public boolean isSessionRenewedOnAuthentication() { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/BasicAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/BasicAuthenticator.java index 2c586efb7ec..d60dcd09901 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/BasicAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/BasicAuthenticator.java @@ -44,18 +44,12 @@ public class BasicAuthenticator extends LoginAuthenticator { } - /** - * @see org.eclipse.jetty.security.Authenticator#getAuthMethod() - */ @Override public String getAuthMethod() { return Constraint.__BASIC_AUTH; } - /** - * @see org.eclipse.jetty.security.Authenticator#validateRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse, boolean) - */ @Override public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DeferredAuthentication.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DeferredAuthentication.java index e81bab6022f..a83d086912d 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DeferredAuthentication.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DeferredAuthentication.java @@ -55,9 +55,6 @@ public class DeferredAuthentication implements Authentication.Deferred this._authenticator = authenticator; } - /** - * @see org.eclipse.jetty.server.Authentication.Deferred#authenticate(ServletRequest) - */ @Override public Authentication authenticate(ServletRequest request) { @@ -83,9 +80,6 @@ public class DeferredAuthentication implements Authentication.Deferred return this; } - /** - * @see org.eclipse.jetty.server.Authentication.Deferred#authenticate(javax.servlet.ServletRequest, javax.servlet.ServletResponse) - */ @Override public Authentication authenticate(ServletRequest request, ServletResponse response) { @@ -106,9 +100,6 @@ public class DeferredAuthentication implements Authentication.Deferred return this; } - /** - * @see org.eclipse.jetty.server.Authentication.Deferred#login(String, Object, ServletRequest) - */ @Override public Authentication login(String username, Object password, ServletRequest request) { diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java index d061079b703..98694577ab2 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java @@ -117,9 +117,6 @@ public class FormAuthenticator extends LoginAuthenticator return _alwaysSaveUri; } - /** - * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration) - */ @Override public void setConfiguration(AuthConfiguration configuration) { diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java index 7d9312fa7bc..2cb0382f398 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java @@ -1747,9 +1747,6 @@ public class ConstraintTest private class RoleRefHandler extends HandlerWrapper { - /** - * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/TestLoginService.java b/jetty-security/src/test/java/org/eclipse/jetty/security/TestLoginService.java index ac0b511ef1c..d54b1dd8dc1 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/TestLoginService.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/TestLoginService.java @@ -43,9 +43,6 @@ public class TestLoginService extends AbstractLoginService userStore.addUser(username, credential, roles); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadRoleInfo(org.eclipse.jetty.security.AbstractLoginService.UserPrincipal) - */ @Override protected String[] loadRoleInfo(UserPrincipal user) { @@ -63,9 +60,6 @@ public class TestLoginService extends AbstractLoginService return list.toArray(new String[roles.size()]); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadUserInfo(java.lang.String) - */ @Override protected UserPrincipal loadUserInfo(String username) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java index 3efc38195db..e10df803048 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java @@ -630,9 +630,6 @@ public class Request implements HttpServletRequest return (_attributes == null) ? null : _attributes.getAttribute(name); } - /* - * @see javax.servlet.ServletRequest#getAttributeNames() - */ @Override public Enumeration getAttributeNames() { @@ -659,9 +656,6 @@ public class Request implements HttpServletRequest return _authentication; } - /* - * @see javax.servlet.http.HttpServletRequest#getAuthType() - */ @Override public String getAuthType() { @@ -673,9 +667,6 @@ public class Request implements HttpServletRequest return null; } - /* - * @see javax.servlet.ServletRequest#getCharacterEncoding() - */ @Override public String getCharacterEncoding() { @@ -707,9 +698,6 @@ public class Request implements HttpServletRequest return _channel; } - /* - * @see javax.servlet.ServletRequest#getContentLength() - */ @Override public int getContentLength() { @@ -733,9 +721,6 @@ public class Request implements HttpServletRequest return (int)metadata.getFields().getLongField(HttpHeader.CONTENT_LENGTH.asString()); } - /* - * @see javax.servlet.ServletRequest.getContentLengthLong() - */ @Override public long getContentLengthLong() { @@ -752,9 +737,6 @@ public class Request implements HttpServletRequest return _input.getContentConsumed(); } - /* - * @see javax.servlet.ServletRequest#getContentType() - */ @Override public String getContentType() { @@ -790,18 +772,12 @@ public class Request implements HttpServletRequest return _errorContext; } - /* - * @see javax.servlet.http.HttpServletRequest#getContextPath() - */ @Override public String getContextPath() { return _contextPath; } - /* - * @see javax.servlet.http.HttpServletRequest#getCookies() - */ @Override public Cookie[] getCookies() { @@ -833,9 +809,6 @@ public class Request implements HttpServletRequest return _cookies.getCookies(); } - /* - * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String) - */ @Override public long getDateHeader(String name) { @@ -849,9 +822,6 @@ public class Request implements HttpServletRequest return _dispatcherType; } - /* - * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String) - */ @Override public String getHeader(String name) { @@ -859,9 +829,6 @@ public class Request implements HttpServletRequest return metadata == null ? null : metadata.getFields().get(name); } - /* - * @see javax.servlet.http.HttpServletRequest#getHeaderNames() - */ @Override public Enumeration getHeaderNames() { @@ -869,9 +836,6 @@ public class Request implements HttpServletRequest return metadata == null ? Collections.emptyEnumeration() : metadata.getFields().getFieldNames(); } - /* - * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String) - */ @Override public Enumeration getHeaders(String name) { @@ -892,9 +856,6 @@ public class Request implements HttpServletRequest return _inputState; } - /* - * @see javax.servlet.ServletRequest#getInputStream() - */ @Override public ServletInputStream getInputStream() throws IOException { @@ -908,9 +869,6 @@ public class Request implements HttpServletRequest return _input; } - /* - * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String) - */ @Override public int getIntHeader(String name) { @@ -918,9 +876,6 @@ public class Request implements HttpServletRequest return metadata == null ? -1 : (int)metadata.getFields().getLongField(name); } - /* - * @see javax.servlet.ServletRequest#getLocale() - */ @Override public Locale getLocale() { @@ -946,9 +901,6 @@ public class Request implements HttpServletRequest return new Locale(language, country); } - /* - * @see javax.servlet.ServletRequest#getLocales() - */ @Override public Enumeration getLocales() { @@ -978,9 +930,6 @@ public class Request implements HttpServletRequest return Collections.enumeration(locales); } - /* - * @see javax.servlet.ServletRequest#getLocalAddr() - */ @Override public String getLocalAddr() { @@ -1008,9 +957,6 @@ public class Request implements HttpServletRequest return address.getHostAddress(); } - /* - * @see javax.servlet.ServletRequest#getLocalName() - */ @Override public String getLocalName() { @@ -1035,9 +981,6 @@ public class Request implements HttpServletRequest return null; } - /* - * @see javax.servlet.ServletRequest#getLocalPort() - */ @Override public int getLocalPort() { @@ -1047,9 +990,6 @@ public class Request implements HttpServletRequest return local == null ? 0 : local.getPort(); } - /* - * @see javax.servlet.http.HttpServletRequest#getMethod() - */ @Override public String getMethod() { @@ -1059,36 +999,24 @@ public class Request implements HttpServletRequest return null; } - /* - * @see javax.servlet.ServletRequest#getParameter(java.lang.String) - */ @Override public String getParameter(String name) { return getParameters().getValue(name, 0); } - /* - * @see javax.servlet.ServletRequest#getParameterMap() - */ @Override public Map getParameterMap() { return Collections.unmodifiableMap(getParameters().toStringArrayMap()); } - /* - * @see javax.servlet.ServletRequest#getParameterNames() - */ @Override public Enumeration getParameterNames() { return Collections.enumeration(getParameters().keySet()); } - /* - * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String) - */ @Override public String[] getParameterValues(String name) { @@ -1118,18 +1046,12 @@ public class Request implements HttpServletRequest _parameters = null; } - /* - * @see javax.servlet.http.HttpServletRequest#getPathInfo() - */ @Override public String getPathInfo() { return _pathInfo; } - /* - * @see javax.servlet.http.HttpServletRequest#getPathTranslated() - */ @Override public String getPathTranslated() { @@ -1138,9 +1060,6 @@ public class Request implements HttpServletRequest return _context.getRealPath(_pathInfo); } - /* - * @see javax.servlet.ServletRequest#getProtocol() - */ @Override public String getProtocol() { @@ -1167,9 +1086,6 @@ public class Request implements HttpServletRequest return _queryEncoding; } - /* - * @see javax.servlet.http.HttpServletRequest#getQueryString() - */ @Override public String getQueryString() { @@ -1177,9 +1093,6 @@ public class Request implements HttpServletRequest return metadata == null ? null : metadata.getURI().getQuery(); } - /* - * @see javax.servlet.ServletRequest#getReader() - */ @Override public BufferedReader getReader() throws IOException { @@ -1234,9 +1147,6 @@ public class Request implements HttpServletRequest return remote; } - /* - * @see javax.servlet.ServletRequest#getRemoteAddr() - */ @Override public String getRemoteAddr() { @@ -1254,9 +1164,6 @@ public class Request implements HttpServletRequest return address.getHostAddress(); } - /* - * @see javax.servlet.ServletRequest#getRemoteHost() - */ @Override public String getRemoteHost() { @@ -1266,9 +1173,6 @@ public class Request implements HttpServletRequest return remote == null ? "" : remote.getHostString(); } - /* - * @see javax.servlet.ServletRequest#getRemotePort() - */ @Override public int getRemotePort() { @@ -1278,9 +1182,6 @@ public class Request implements HttpServletRequest return remote == null ? 0 : remote.getPort(); } - /* - * @see javax.servlet.http.HttpServletRequest#getRemoteUser() - */ @Override public String getRemoteUser() { @@ -1290,9 +1191,6 @@ public class Request implements HttpServletRequest return p.getName(); } - /* - * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String) - */ @Override public RequestDispatcher getRequestDispatcher(String path) { @@ -1318,18 +1216,12 @@ public class Request implements HttpServletRequest return _context.getRequestDispatcher(path); } - /* - * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId() - */ @Override public String getRequestedSessionId() { return _requestedSessionId; } - /* - * @see javax.servlet.http.HttpServletRequest#getRequestURI() - */ @Override public String getRequestURI() { @@ -1337,9 +1229,6 @@ public class Request implements HttpServletRequest return metadata == null ? null : metadata.getURI().getPath(); } - /* - * @see javax.servlet.http.HttpServletRequest#getRequestURL() - */ @Override public StringBuffer getRequestURL() { @@ -1371,9 +1260,6 @@ public class Request implements HttpServletRequest return url; } - /* - * @see javax.servlet.ServletRequest#getScheme() - */ @Override public String getScheme() { @@ -1382,9 +1268,6 @@ public class Request implements HttpServletRequest return scheme == null ? HttpScheme.HTTP.asString() : scheme; } - /* - * @see javax.servlet.ServletRequest#getServerName() - */ @Override public String getServerName() { @@ -1417,9 +1300,6 @@ public class Request implements HttpServletRequest return null; } - /* - * @see javax.servlet.ServletRequest#getServerPort() - */ @Override public int getServerPort() { @@ -1461,9 +1341,6 @@ public class Request implements HttpServletRequest return null; } - /* - * @see javax.servlet.http.HttpServletRequest#getServletPath() - */ @Override public String getServletPath() { @@ -1564,18 +1441,12 @@ public class Request implements HttpServletRequest return session; } - /* - * @see javax.servlet.http.HttpServletRequest#getSession() - */ @Override public HttpSession getSession() { return getSession(true); } - /* - * @see javax.servlet.http.HttpServletRequest#getSession(boolean) - */ @Override public HttpSession getSession(boolean create) { @@ -1675,9 +1546,6 @@ public class Request implements HttpServletRequest return _scope; } - /* - * @see javax.servlet.http.HttpServletRequest#getUserPrincipal() - */ @Override public Principal getUserPrincipal() { @@ -1710,18 +1578,12 @@ public class Request implements HttpServletRequest return _asyncNotSupportedSource == null; } - /* - * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie() - */ @Override public boolean isRequestedSessionIdFromCookie() { return _requestedSessionId != null && _requestedSessionIdFromCookie; } - /* - * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl() - */ @Override @Deprecated(since = "Servlet API 2.1") public boolean isRequestedSessionIdFromUrl() @@ -1729,18 +1591,12 @@ public class Request implements HttpServletRequest return _requestedSessionId != null && !_requestedSessionIdFromCookie; } - /* - * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL() - */ @Override public boolean isRequestedSessionIdFromURL() { return _requestedSessionId != null && !_requestedSessionIdFromCookie; } - /* - * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid() - */ @Override public boolean isRequestedSessionIdValid() { @@ -1751,9 +1607,6 @@ public class Request implements HttpServletRequest return (session != null && _sessionHandler.getSessionIdManager().getId(_requestedSessionId).equals(_sessionHandler.getId(session))); } - /* - * @see javax.servlet.ServletRequest#isSecure() - */ @Override public boolean isSecure() { @@ -1765,9 +1618,6 @@ public class Request implements HttpServletRequest _secure = secure; } - /* - * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String) - */ @Override public boolean isUserInRole(String role) { @@ -1907,9 +1757,6 @@ public class Request implements HttpServletRequest _requestAttributeListeners.clear(); } - /* - * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String) - */ @Override public void removeAttribute(String name) { @@ -1938,7 +1785,7 @@ public class Request implements HttpServletRequest _asyncNotSupportedSource = supported ? null : (source == null ? "unknown" : source); } - /* + /** * Set a request attribute. if the attribute name is "org.eclipse.jetty.server.server.Request.queryEncoding" then the value is also passed in a call to * {@link #setQueryEncoding}. * @@ -1988,9 +1835,6 @@ public class Request implements HttpServletRequest _authentication = authentication; } - /* - * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String) - */ @Override public void setCharacterEncoding(String encoding) throws UnsupportedEncodingException { @@ -2491,9 +2335,6 @@ public class Request implements HttpServletRequest } } - /** - * @see javax.servlet.http.HttpServletRequest#upgrade(java.lang.Class) - */ @Override public T upgrade(Class handlerClass) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java index bc0063c8e5f..431fe297598 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java @@ -612,45 +612,30 @@ public class Server extends HandlerWrapper implements Attributes _sessionIdManager = sessionIdManager; } - /* - * @see org.eclipse.util.AttributesMap#clearAttributes() - */ @Override public void clearAttributes() { _attributes.clearAttributes(); } - /* - * @see org.eclipse.util.AttributesMap#getAttribute(java.lang.String) - */ @Override public Object getAttribute(String name) { return _attributes.getAttribute(name); } - /* - * @see org.eclipse.util.AttributesMap#getAttributeNames() - */ @Override public Enumeration getAttributeNames() { return _attributes.getAttributeNames(); } - /* - * @see org.eclipse.util.AttributesMap#removeAttribute(java.lang.String) - */ @Override public void removeAttribute(String name) { _attributes.removeAttribute(name); } - /* - * @see org.eclipse.util.AttributesMap#setAttribute(java.lang.String, java.lang.Object) - */ @Override public void setAttribute(String name, Object attribute) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletRequestHttpWrapper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletRequestHttpWrapper.java index e672e62afc2..3d6030c9620 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletRequestHttpWrapper.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletRequestHttpWrapper.java @@ -195,54 +195,36 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements return false; } - /** - * @see javax.servlet.http.HttpServletRequest#authenticate(javax.servlet.http.HttpServletResponse) - */ @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return false; } - /** - * @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String) - */ @Override public Part getPart(String name) throws IOException, ServletException { return null; } - /** - * @see javax.servlet.http.HttpServletRequest#getParts() - */ @Override public Collection getParts() throws IOException, ServletException { return null; } - /** - * @see javax.servlet.http.HttpServletRequest#login(java.lang.String, java.lang.String) - */ @Override public void login(String username, String password) throws ServletException { } - /** - * @see javax.servlet.http.HttpServletRequest#logout() - */ @Override public void logout() throws ServletException { } - /** - * @see javax.servlet.http.HttpServletRequest#changeSessionId() - */ @Override public String changeSessionId() { @@ -250,9 +232,6 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements return null; } - /** - * @see javax.servlet.http.HttpServletRequest#upgrade(java.lang.Class) - */ @Override public T upgrade(Class handlerClass) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletResponseHttpWrapper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletResponseHttpWrapper.java index 7bfa50290ee..31787ba0fbd 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletResponseHttpWrapper.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletResponseHttpWrapper.java @@ -130,36 +130,24 @@ public class ServletResponseHttpWrapper extends ServletResponseWrapper implement { } - /** - * @see javax.servlet.http.HttpServletResponse#getHeader(java.lang.String) - */ @Override public String getHeader(String name) { return null; } - /** - * @see javax.servlet.http.HttpServletResponse#getHeaderNames() - */ @Override public Collection getHeaderNames() { return null; } - /** - * @see javax.servlet.http.HttpServletResponse#getHeaders(java.lang.String) - */ @Override public Collection getHeaders(String name) { return null; } - /** - * @see javax.servlet.http.HttpServletResponse#getStatus() - */ @Override public int getStatus() { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandler.java index 749dd51230a..f04b6630cba 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandler.java @@ -84,9 +84,6 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand baseRequest.setHandled(true); } - /* - * @see org.eclipse.thread.LifeCycle#start() - */ @Override protected void doStart() throws Exception { @@ -97,9 +94,6 @@ public abstract class AbstractHandler extends ContainerLifeCycle implements Hand super.doStart(); } - /* - * @see org.eclipse.thread.LifeCycle#stop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/BufferedResponseHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/BufferedResponseHandler.java index 07721ac4627..400d4f6b819 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/BufferedResponseHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/BufferedResponseHandler.java @@ -100,9 +100,6 @@ public class BufferedResponseHandler extends HandlerWrapper return _mimeTypes; } - /** - * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java index 4f3e2050d4e..c98dfbc3d48 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java @@ -477,18 +477,12 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return vhosts; } - /* - * @see javax.servlet.ServletContext#getAttribute(java.lang.String) - */ @Override public Object getAttribute(String name) { return _attributes.getAttribute(name); } - /* - * @see javax.servlet.ServletContext#getAttributeNames() - */ @Override public Enumeration getAttributeNames() { @@ -747,9 +741,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu _logger = logger; } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -904,9 +895,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu l.contextDestroyed(e); } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { @@ -1080,10 +1068,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return true; } - /** - * @see org.eclipse.jetty.server.handler.ScopedHandler#doScope(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) - */ @Override public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { @@ -1229,10 +1213,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu } } - /** - * @see org.eclipse.jetty.server.handler.ScopedHandler#doHandle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse) - */ @Override public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { @@ -1414,9 +1394,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return Arrays.copyOf(_protectedTargets, _protectedTargets.length); } - /* - * @see javax.servlet.ServletContext#removeAttribute(java.lang.String) - */ @Override public void removeAttribute(String name) { @@ -1988,9 +1965,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return ContextHandler.this; } - /* - * @see javax.servlet.ServletContext#getContext(java.lang.String) - */ @Override public ServletContext getContext(String uripath) { @@ -2077,9 +2051,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return null; } - /* - * @see javax.servlet.ServletContext#getMimeType(java.lang.String) - */ @Override public String getMimeType(String file) { @@ -2088,9 +2059,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return _mimeTypes.getMimeByExtension(file); } - /* - * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String) - */ @Override public RequestDispatcher getRequestDispatcher(String uriInContext) { @@ -2123,9 +2091,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return null; } - /* - * @see javax.servlet.ServletContext#getRealPath(java.lang.String) - */ @Override public String getRealPath(String path) { @@ -2163,9 +2128,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return null; } - /* - * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String) - */ @Override public InputStream getResourceAsStream(String path) { @@ -2187,36 +2149,24 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu } } - /* - * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String) - */ @Override public Set getResourcePaths(String path) { return ContextHandler.this.getResourcePaths(path); } - /* - * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String) - */ @Override public void log(Exception exception, String msg) { _logger.warn(msg, exception); } - /* - * @see javax.servlet.ServletContext#log(java.lang.String) - */ @Override public void log(String msg) { _logger.info(msg); } - /* - * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable) - */ @Override public void log(String message, Throwable throwable) { @@ -2226,27 +2176,18 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu _logger.warn(message, throwable); } - /* - * @see javax.servlet.ServletContext#getInitParameter(java.lang.String) - */ @Override public String getInitParameter(String name) { return ContextHandler.this.getInitParameter(name); } - /* - * @see javax.servlet.ServletContext#getInitParameterNames() - */ @Override public Enumeration getInitParameterNames() { return ContextHandler.this.getInitParameterNames(); } - /* - * @see javax.servlet.ServletContext#getAttribute(java.lang.String) - */ @Override public synchronized Object getAttribute(String name) { @@ -2256,9 +2197,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return o; } - /* - * @see javax.servlet.ServletContext#getAttributeNames() - */ @Override public synchronized Enumeration getAttributeNames() { @@ -2277,9 +2215,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu return Collections.enumeration(set); } - /* - * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object) - */ @Override public synchronized void setAttribute(String name, Object value) { @@ -2306,9 +2241,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu } } - /* - * @see javax.servlet.ServletContext#removeAttribute(java.lang.String) - */ @Override public synchronized void removeAttribute(String name) { @@ -2325,9 +2257,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu } } - /* - * @see javax.servlet.ServletContext#getServletContextName() - */ @Override public String getServletContextName() { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DebugHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DebugHandler.java index 5ec6e7419a6..0690f20b628 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DebugHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DebugHandler.java @@ -47,9 +47,6 @@ public class DebugHandler extends HandlerWrapper implements Connection.Listener private OutputStream _out; private PrintStream _print; - /* - * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -120,9 +117,6 @@ public class DebugHandler extends HandlerWrapper implements Connection.Listener _print.println(d + (ms > 99 ? "." : (ms > 9 ? ".0" : ".00")) + ms + ":" + name + " " + message); } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.handler.HandlerWrapper#doStart() - */ @Override protected void doStart() throws Exception { @@ -139,9 +133,6 @@ public class DebugHandler extends HandlerWrapper implements Connection.Listener super.doStart(); } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.handler.HandlerWrapper#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java index a25f005c8ce..839f25faa62 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java @@ -81,9 +81,6 @@ public class DefaultHandler extends AbstractHandler } } - /* - * @see org.eclipse.jetty.server.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java index 246ef835f9f..2507ea9322e 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerList.java @@ -43,9 +43,6 @@ public class HandlerList extends HandlerCollection super(handlers); } - /** - * @see Handler#handle(String, Request, HttpServletRequest, HttpServletResponse) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java index a8bbfae997d..162d1ce3f89 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java @@ -81,27 +81,18 @@ public class HotSwapHandler extends AbstractHandlerContainer } } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { super.doStart(); } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { super.doStop(); } - /* - * @see org.eclipse.jetty.server.server.EventHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/RequestLogHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/RequestLogHandler.java index f9f365898e7..5e8bf28eebd 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/RequestLogHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/RequestLogHandler.java @@ -41,9 +41,6 @@ public class RequestLogHandler extends HandlerWrapper { private RequestLog _requestLog; - /* - * @see org.eclipse.jetty.server.server.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java index 3173ee51a8f..6d99bc10479 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java @@ -214,9 +214,6 @@ public class ResourceHandler extends HandlerWrapper implements ResourceFactory, return _welcomes; } - /* - * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java index 20f06162f1d..92a157d915b 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java @@ -105,9 +105,6 @@ public abstract class ScopedHandler extends HandlerWrapper protected ScopedHandler _outerScope; protected ScopedHandler _nextScope; - /** - * @see org.eclipse.jetty.server.handler.HandlerWrapper#doStart() - */ @Override protected void doStart() throws Exception { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionCache.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionCache.java index 78bb7b5349a..db995aefdff 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionCache.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionCache.java @@ -183,9 +183,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements return _handler; } - /** - * @see org.eclipse.jetty.server.session.SessionCache#initialize(org.eclipse.jetty.server.session.SessionContext) - */ @Override public void initialize(SessionContext context) { @@ -194,9 +191,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements _context = context; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -213,9 +207,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements super.doStart(); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { @@ -232,9 +223,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements return _sessionDataStore; } - /** - * @see org.eclipse.jetty.server.session.SessionCache#setSessionDataStore(org.eclipse.jetty.server.session.SessionDataStore) - */ @Override public void setSessionDataStore(SessionDataStore sessionStore) { @@ -669,9 +657,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements return doDelete(id); } - /** - * @see org.eclipse.jetty.server.session.SessionCache#checkExpiration(Set) - */ @Override public Set checkExpiration(Set candidates) { @@ -806,9 +791,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements } } - /** - * @see org.eclipse.jetty.server.session.SessionCache#setSaveOnInactiveEviction(boolean) - */ @Override public void setSaveOnInactiveEviction(boolean saveOnEvict) { @@ -828,9 +810,6 @@ public abstract class AbstractSessionCache extends ContainerLifeCycle implements return _saveOnInactiveEviction; } - /** - * @see org.eclipse.jetty.server.session.SessionCache#newSession(javax.servlet.http.HttpServletRequest, java.lang.String, long, long) - */ @Override public Session newSession(HttpServletRequest request, String id, long time, long maxInactiveMs) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStore.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStore.java index 708d6a29b08..68a235047b6 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStore.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStore.java @@ -83,9 +83,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi return _cache; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#load(java.lang.String) - */ @Override public SessionData load(String id) throws Exception { @@ -110,9 +107,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi return d; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#delete(java.lang.String) - */ @Override public boolean delete(String id) throws Exception { @@ -124,9 +118,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi return deleted; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#getExpired(Set) - */ @Override public Set getExpired(Set candidates) { @@ -134,9 +125,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi return _store.getExpired(candidates); } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#store(java.lang.String, org.eclipse.jetty.server.session.SessionData) - */ @Override public void store(String id, SessionData data) throws Exception { @@ -162,18 +150,12 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi super.doStop(); } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#isPassivating() - */ @Override public boolean isPassivating() { return _store.isPassivating(); } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#exists(java.lang.String) - */ @Override public boolean exists(String id) throws Exception { @@ -193,9 +175,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi return _store.exists(id); } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#initialize(org.eclipse.jetty.server.session.SessionContext) - */ @Override public void initialize(SessionContext context) throws Exception { @@ -204,9 +183,6 @@ public class CachingSessionDataStore extends ContainerLifeCycle implements Sessi _cache.initialize(context); } - /** - * @see org.eclipse.jetty.server.session.SessionDataStore#newSessionData(java.lang.String, long, long, long, long) - */ @Override public SessionData newSessionData(String id, long created, long accessed, long lastAccessed, long maxInactiveMs) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStoreFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStoreFactory.java index 9155ebd94b7..0236e5e6fd2 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStoreFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/CachingSessionDataStoreFactory.java @@ -56,9 +56,6 @@ public class CachingSessionDataStoreFactory extends AbstractSessionDataStoreFact _sessionStoreFactory = factory; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DatabaseAdaptor.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DatabaseAdaptor.java index b71b424ab4a..a0d68c2dc05 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DatabaseAdaptor.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DatabaseAdaptor.java @@ -305,9 +305,6 @@ public class DatabaseAdaptor return DriverManager.getConnection(_connectionUrl); } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java index f9f7fc6fbe5..1a4dffee910 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java @@ -274,9 +274,6 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi return id; } - /** - * @see org.eclipse.jetty.server.SessionIdManager#isIdInUse(java.lang.String) - */ @Override public boolean isIdInUse(String id) { @@ -312,9 +309,6 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi } } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -344,9 +338,6 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi _houseKeeper.start(); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { @@ -488,9 +479,6 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi return handlers; } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/FileSessionDataStoreFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/FileSessionDataStoreFactory.java index a07a4542ff5..2f386528d76 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/FileSessionDataStoreFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/FileSessionDataStoreFactory.java @@ -60,9 +60,6 @@ public class FileSessionDataStoreFactory extends AbstractSessionDataStoreFactory _storeDir = storeDir; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java index b49aa79b16c..23bd6ddf942 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java @@ -78,9 +78,6 @@ public class HouseKeeper extends AbstractLifeCycle _sessionIdManager = sessionIdManager; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -167,9 +164,6 @@ public class HouseKeeper extends AbstractLifeCycle _runner = null; } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { @@ -263,9 +257,6 @@ public class HouseKeeper extends AbstractLifeCycle } } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionDataStoreFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionDataStoreFactory.java index 8d1f375ce59..14a903f0cc1 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionDataStoreFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionDataStoreFactory.java @@ -34,9 +34,6 @@ public class JDBCSessionDataStoreFactory extends AbstractSessionDataStoreFactory */ JDBCSessionDataStore.SessionTableSchema _schema; - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/NullSessionDataStoreFactory.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/NullSessionDataStoreFactory.java index 642a5bf31c7..a8e083cdf24 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/NullSessionDataStoreFactory.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/NullSessionDataStoreFactory.java @@ -24,9 +24,6 @@ package org.eclipse.jetty.server.session; public class NullSessionDataStoreFactory extends AbstractSessionDataStoreFactory { - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java index ecfce716f17..0bf1d322369 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java @@ -445,9 +445,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#getId() - */ @Override public String getId() { @@ -472,9 +469,6 @@ public class Session implements SessionHandler.SessionIf return _sessionData.getVhost(); } - /** - * @see javax.servlet.http.HttpSession#getLastAccessedTime() - */ @Override public long getLastAccessedTime() { @@ -488,9 +482,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#getServletContext() - */ @Override public ServletContext getServletContext() { @@ -499,9 +490,6 @@ public class Session implements SessionHandler.SessionIf return _handler._context; } - /** - * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int) - */ @Override public void setMaxInactiveInterval(int secs) { @@ -596,9 +584,6 @@ public class Session implements SessionHandler.SessionIf return time; } - /** - * @see javax.servlet.http.HttpSession#getMaxInactiveInterval() - */ @Override public int getMaxInactiveInterval() { @@ -609,9 +594,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#getSessionContext() - */ @Override @Deprecated(since = "Servlet API 2.1") public HttpSessionContext getSessionContext() @@ -670,9 +652,6 @@ public class Session implements SessionHandler.SessionIf throw new IllegalStateException("Invalid for read: id=" + _sessionData.getId() + " not resident"); } - /** - * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String) - */ @Override public Object getAttribute(String name) { @@ -683,9 +662,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#getValue(java.lang.String) - */ @Override @Deprecated(since = "Servlet API 2.2") public Object getValue(String name) @@ -697,9 +673,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#getAttributeNames() - */ @Override public Enumeration getAttributeNames() { @@ -758,10 +731,6 @@ public class Session implements SessionHandler.SessionIf } } - /** - * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String, - * java.lang.Object) - */ @Override public void setAttribute(String name, Object value) { @@ -778,10 +747,6 @@ public class Session implements SessionHandler.SessionIf callSessionAttributeListeners(name, value, old); } - /** - * @see javax.servlet.http.HttpSession#putValue(java.lang.String, - * java.lang.Object) - */ @Override @Deprecated(since = "Servlet API 2.2") public void putValue(String name, Object value) @@ -789,18 +754,12 @@ public class Session implements SessionHandler.SessionIf setAttribute(name, value); } - /** - * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String) - */ @Override public void removeAttribute(String name) { setAttribute(name, null); } - /** - * @see javax.servlet.http.HttpSession#removeValue(java.lang.String) - */ @Override @Deprecated(since = "Servlet API 2.1") public void removeValue(String name) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java index efb3cb72d9e..4477530055c 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java @@ -386,9 +386,6 @@ public class SessionHandler extends ScopedHandler } } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -489,9 +486,6 @@ public class SessionHandler extends ScopedHandler super.doStart(); } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { @@ -1476,9 +1470,6 @@ public class SessionHandler extends ScopedHandler } } - /* - * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1574,9 +1565,6 @@ public class SessionHandler extends ScopedHandler } } - /* - * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) - */ @Override public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1698,9 +1686,6 @@ public class SessionHandler extends ScopedHandler } } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java index 60c1bdad48c..a2dc1a77357 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java @@ -203,9 +203,6 @@ public abstract class ConnectorCloseTestBase extends HttpServerTestFixture return _response; } - /** - * @see java.lang.Runnable#run() - */ @Override public void run() { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java index 078331af7c6..f725b1f27a9 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/DefaultServlet.java @@ -462,9 +462,6 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory, Welc doGet(request, response); } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -478,9 +475,6 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory, Welc resp.setHeader("Allow", "GET,HEAD,POST,OPTIONS"); } - /* - * @see javax.servlet.Servlet#destroy() - */ @Override public void destroy() { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/NoJspServlet.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/NoJspServlet.java index 2a13dab5848..153cbff20d3 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/NoJspServlet.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/NoJspServlet.java @@ -28,9 +28,6 @@ public class NoJspServlet extends HttpServlet { private boolean _warned; - /* - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletContextHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletContextHandler.java index 7ce95f9709f..b082327e7c5 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletContextHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletContextHandler.java @@ -31,7 +31,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; - import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.FilterRegistration; @@ -42,7 +41,6 @@ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.ServletSecurityElement; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; @@ -319,9 +317,6 @@ public class ServletContextHandler extends ContextHandler super.doStart(); } - /** - * @see org.eclipse.jetty.server.handler.ContextHandler#doStop() - */ @Override protected void doStop() throws Exception { @@ -761,9 +756,6 @@ public class ServletContextHandler extends ContextHandler private String _buffer; private String _errorOnUndeclaredNamespace; - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getUrlPatterns() - */ @Override public Collection getUrlPatterns() { @@ -776,9 +768,6 @@ public class ServletContextHandler extends ContextHandler _urlPatterns.add(s); } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getElIgnored() - */ @Override public String getElIgnored() { @@ -790,9 +779,6 @@ public class ServletContextHandler extends ContextHandler _elIgnored = s; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getPageEncoding() - */ @Override public String getPageEncoding() { @@ -839,27 +825,18 @@ public class ServletContextHandler extends ContextHandler _errorOnUndeclaredNamespace = errorOnUndeclaredNamespace; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getScriptingInvalid() - */ @Override public String getScriptingInvalid() { return _scriptingInvalid; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getIsXml() - */ @Override public String getIsXml() { return _isXml; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getIncludePreludes() - */ @Override public Collection getIncludePreludes() { @@ -872,9 +849,6 @@ public class ServletContextHandler extends ContextHandler _includePreludes.add(prelude); } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getIncludeCodas() - */ @Override public Collection getIncludeCodas() { @@ -887,45 +861,30 @@ public class ServletContextHandler extends ContextHandler _includeCodas.add(coda); } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getDeferredSyntaxAllowedAsLiteral() - */ @Override public String getDeferredSyntaxAllowedAsLiteral() { return _deferredSyntaxAllowedAsLiteral; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getTrimDirectiveWhitespaces() - */ @Override public String getTrimDirectiveWhitespaces() { return _trimDirectiveWhitespaces; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getDefaultContentType() - */ @Override public String getDefaultContentType() { return _defaultContentType; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getBuffer() - */ @Override public String getBuffer() { return _buffer; } - /** - * @see javax.servlet.descriptor.JspPropertyGroupDescriptor#getErrorOnUndeclaredNamespace() - */ @Override public String getErrorOnUndeclaredNamespace() { @@ -963,9 +922,6 @@ public class ServletContextHandler extends ContextHandler private String _uri; private String _location; - /** - * @see javax.servlet.descriptor.TaglibDescriptor#getTaglibURI() - */ @Override public String getTaglibURI() { @@ -977,9 +933,6 @@ public class ServletContextHandler extends ContextHandler _uri = uri; } - /** - * @see javax.servlet.descriptor.TaglibDescriptor#getTaglibLocation() - */ @Override public String getTaglibLocation() { @@ -1007,9 +960,6 @@ public class ServletContextHandler extends ContextHandler { } - /** - * @see javax.servlet.descriptor.JspConfigDescriptor#getTaglibs() - */ @Override public Collection getTaglibs() { @@ -1021,9 +971,6 @@ public class ServletContextHandler extends ContextHandler _taglibs.add(d); } - /** - * @see javax.servlet.descriptor.JspConfigDescriptor#getJspPropertyGroups() - */ @Override public Collection getJspPropertyGroups() { @@ -1054,9 +1001,6 @@ public class ServletContextHandler extends ContextHandler public class Context extends ContextHandler.Context { - /* - * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String) - */ @Override public RequestDispatcher getNamedDispatcher(String name) { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java index 87c6639a152..21836414996 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java @@ -650,18 +650,12 @@ public class ServletHolder extends Holder implements UserIdentity.Scope return ContextHandler.getContextHandler(_config.getServletContext()); } - /** - * @see org.eclipse.jetty.server.UserIdentity.Scope#getContextPath() - */ @Override public String getContextPath() { return _config.getServletContext().getContextPath(); } - /** - * @see org.eclipse.jetty.server.UserIdentity.Scope#getRoleRefMap() - */ @Override public Map getRoleRefMap() { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Source.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Source.java index e2419c8b6ed..8d8306004f9 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Source.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Source.java @@ -65,9 +65,6 @@ public class Source return _resource; } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/HostMap.java b/jetty-util/src/main/java/org/eclipse/jetty/util/HostMap.java index 8acd4e41b0b..bedb25cc66a 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/HostMap.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/HostMap.java @@ -47,9 +47,6 @@ public class HostMap extends HashMap super(capacity); } - /** - * @see java.util.HashMap#put(java.lang.Object, java.lang.Object) - */ @Override public TYPE put(String host, TYPE object) throws IllegalArgumentException @@ -57,9 +54,6 @@ public class HostMap extends HashMap return super.put(host, object); } - /** - * @see java.util.HashMap#get(java.lang.Object) - */ @Override public TYPE get(Object key) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java b/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java index ebbe7049802..5f6861295c4 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/IO.java @@ -78,9 +78,6 @@ public class IO this.write = write; } - /* - * @see java.lang.Runnable#run() - */ @Override public void run() { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/PathWatcher.java b/jetty-util/src/main/java/org/eclipse/jetty/util/PathWatcher.java index f7a0e9016aa..66b6979b0fb 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/PathWatcher.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/PathWatcher.java @@ -628,9 +628,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable config.setPauseUntil(now + getUpdateQuietTimeMillis()); } - /** - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(Object obj) { @@ -675,9 +672,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable return type; } - /** - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { @@ -688,9 +682,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable return result; } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { @@ -864,9 +855,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable s.append("]"); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { @@ -896,9 +884,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable super.doStart(); } - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() - */ @Override protected void doStop() throws Exception { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java index f4546badfc6..34dfd80c925 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java @@ -973,9 +973,6 @@ public class UrlEncoded extends MultiMap implements Cloneable return new String(encoded, 0, n, charset); } - /** - * - */ @Override public Object clone() { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/log/JettyAwareLogger.java b/jetty-util/src/main/java/org/eclipse/jetty/util/log/JettyAwareLogger.java index 9271cbc577c..f4021798185 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/log/JettyAwareLogger.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/log/JettyAwareLogger.java @@ -44,369 +44,246 @@ class JettyAwareLogger implements org.slf4j.Logger _logger = logger; } - /** - * @see org.slf4j.Logger#debug(java.lang.String) - */ @Override public void debug(String msg) { log(null, DEBUG, msg, null, null); } - /** - * @see org.slf4j.Logger#debug(java.lang.String, java.lang.Object) - */ @Override public void debug(String format, Object arg) { log(null, DEBUG, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#debug(java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void debug(String format, Object arg1, Object arg2) { log(null, DEBUG, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#debug(java.lang.String, java.lang.Object[]) - */ @Override public void debug(String format, Object[] argArray) { log(null, DEBUG, format, argArray, null); } - /** - * @see org.slf4j.Logger#debug(java.lang.String, java.lang.Throwable) - */ @Override public void debug(String msg, Throwable t) { log(null, DEBUG, msg, null, t); } - /** - * @see org.slf4j.Logger#debug(org.slf4j.Marker, java.lang.String) - */ @Override public void debug(Marker marker, String msg) { log(marker, DEBUG, msg, null, null); } - /** - * @see org.slf4j.Logger#debug(org.slf4j.Marker, java.lang.String, java.lang.Object) - */ @Override public void debug(Marker marker, String format, Object arg) { log(marker, DEBUG, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#debug(org.slf4j.Marker, java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { log(marker, DEBUG, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#debug(org.slf4j.Marker, java.lang.String, java.lang.Object[]) - */ @Override public void debug(Marker marker, String format, Object[] argArray) { log(marker, DEBUG, format, argArray, null); } - /** - * @see org.slf4j.Logger#debug(org.slf4j.Marker, java.lang.String, java.lang.Throwable) - */ @Override public void debug(Marker marker, String msg, Throwable t) { log(marker, DEBUG, msg, null, t); } - /** - * @see org.slf4j.Logger#error(java.lang.String) - */ @Override public void error(String msg) { log(null, ERROR, msg, null, null); } - /** - * @see org.slf4j.Logger#error(java.lang.String, java.lang.Object) - */ @Override public void error(String format, Object arg) { log(null, ERROR, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#error(java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void error(String format, Object arg1, Object arg2) { log(null, ERROR, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#error(java.lang.String, java.lang.Object[]) - */ @Override public void error(String format, Object[] argArray) { log(null, ERROR, format, argArray, null); } - /** - * @see org.slf4j.Logger#error(java.lang.String, java.lang.Throwable) - */ @Override public void error(String msg, Throwable t) { log(null, ERROR, msg, null, t); } - /** - * @see org.slf4j.Logger#error(org.slf4j.Marker, java.lang.String) - */ @Override public void error(Marker marker, String msg) { log(marker, ERROR, msg, null, null); } - /** - * @see org.slf4j.Logger#error(org.slf4j.Marker, java.lang.String, java.lang.Object) - */ @Override public void error(Marker marker, String format, Object arg) { log(marker, ERROR, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#error(org.slf4j.Marker, java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void error(Marker marker, String format, Object arg1, Object arg2) { log(marker, ERROR, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#error(org.slf4j.Marker, java.lang.String, java.lang.Object[]) - */ @Override public void error(Marker marker, String format, Object[] argArray) { log(marker, ERROR, format, argArray, null); } - /** - * @see org.slf4j.Logger#error(org.slf4j.Marker, java.lang.String, java.lang.Throwable) - */ @Override public void error(Marker marker, String msg, Throwable t) { log(marker, ERROR, msg, null, t); } - /** - * @see org.slf4j.Logger#getName() - */ @Override public String getName() { return _logger.getName(); } - /** - * @see org.slf4j.Logger#info(java.lang.String) - */ @Override public void info(String msg) { log(null, INFO, msg, null, null); } - /** - * @see org.slf4j.Logger#info(java.lang.String, java.lang.Object) - */ @Override public void info(String format, Object arg) { log(null, INFO, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#info(java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void info(String format, Object arg1, Object arg2) { log(null, INFO, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#info(java.lang.String, java.lang.Object[]) - */ @Override public void info(String format, Object[] argArray) { log(null, INFO, format, argArray, null); } - /** - * @see org.slf4j.Logger#info(java.lang.String, java.lang.Throwable) - */ @Override public void info(String msg, Throwable t) { log(null, INFO, msg, null, t); } - /** - * @see org.slf4j.Logger#info(org.slf4j.Marker, java.lang.String) - */ @Override public void info(Marker marker, String msg) { log(marker, INFO, msg, null, null); } - /** - * @see org.slf4j.Logger#info(org.slf4j.Marker, java.lang.String, java.lang.Object) - */ @Override public void info(Marker marker, String format, Object arg) { log(marker, INFO, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#info(org.slf4j.Marker, java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void info(Marker marker, String format, Object arg1, Object arg2) { log(marker, INFO, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#info(org.slf4j.Marker, java.lang.String, java.lang.Object[]) - */ @Override public void info(Marker marker, String format, Object[] argArray) { log(marker, INFO, format, argArray, null); } - /** - * @see org.slf4j.Logger#info(org.slf4j.Marker, java.lang.String, java.lang.Throwable) - */ @Override public void info(Marker marker, String msg, Throwable t) { log(marker, INFO, msg, null, t); } - /** - * @see org.slf4j.Logger#isDebugEnabled() - */ @Override public boolean isDebugEnabled() { return _logger.isDebugEnabled(); } - /** - * @see org.slf4j.Logger#isDebugEnabled(org.slf4j.Marker) - */ @Override public boolean isDebugEnabled(Marker marker) { return _logger.isDebugEnabled(marker); } - /** - * @see org.slf4j.Logger#isErrorEnabled() - */ @Override public boolean isErrorEnabled() { return _logger.isErrorEnabled(); } - /** - * @see org.slf4j.Logger#isErrorEnabled(org.slf4j.Marker) - */ @Override public boolean isErrorEnabled(Marker marker) { return _logger.isErrorEnabled(marker); } - /** - * @see org.slf4j.Logger#isInfoEnabled() - */ @Override public boolean isInfoEnabled() { return _logger.isInfoEnabled(); } - /** - * @see org.slf4j.Logger#isInfoEnabled(org.slf4j.Marker) - */ @Override public boolean isInfoEnabled(Marker marker) { return _logger.isInfoEnabled(marker); } - /** - * @see org.slf4j.Logger#isTraceEnabled() - */ @Override public boolean isTraceEnabled() { return _logger.isTraceEnabled(); } - /** - * @see org.slf4j.Logger#isTraceEnabled(org.slf4j.Marker) - */ @Override public boolean isTraceEnabled(Marker marker) { return _logger.isTraceEnabled(marker); } - /** - * @see org.slf4j.Logger#isWarnEnabled() - */ @Override public boolean isWarnEnabled() { return _logger.isWarnEnabled(); } - /** - * @see org.slf4j.Logger#isWarnEnabled(org.slf4j.Marker) - */ @Override public boolean isWarnEnabled(Marker marker) { @@ -419,180 +296,120 @@ class JettyAwareLogger implements org.slf4j.Logger return _logger.toString(); } - /** - * @see org.slf4j.Logger#trace(java.lang.String) - */ @Override public void trace(String msg) { log(null, TRACE, msg, null, null); } - /** - * @see org.slf4j.Logger#trace(java.lang.String, java.lang.Object) - */ @Override public void trace(String format, Object arg) { log(null, TRACE, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#trace(java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void trace(String format, Object arg1, Object arg2) { log(null, TRACE, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#trace(java.lang.String, java.lang.Object[]) - */ @Override public void trace(String format, Object[] argArray) { log(null, TRACE, format, argArray, null); } - /** - * @see org.slf4j.Logger#trace(java.lang.String, java.lang.Throwable) - */ @Override public void trace(String msg, Throwable t) { log(null, TRACE, msg, null, t); } - /** - * @see org.slf4j.Logger#trace(org.slf4j.Marker, java.lang.String) - */ @Override public void trace(Marker marker, String msg) { log(marker, TRACE, msg, null, null); } - /** - * @see org.slf4j.Logger#trace(org.slf4j.Marker, java.lang.String, java.lang.Object) - */ @Override public void trace(Marker marker, String format, Object arg) { log(marker, TRACE, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#trace(org.slf4j.Marker, java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { log(marker, TRACE, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#trace(org.slf4j.Marker, java.lang.String, java.lang.Object[]) - */ @Override public void trace(Marker marker, String format, Object[] argArray) { log(marker, TRACE, format, argArray, null); } - /** - * @see org.slf4j.Logger#trace(org.slf4j.Marker, java.lang.String, java.lang.Throwable) - */ @Override public void trace(Marker marker, String msg, Throwable t) { log(marker, TRACE, msg, null, t); } - /** - * @see org.slf4j.Logger#warn(java.lang.String) - */ @Override public void warn(String msg) { log(null, WARN, msg, null, null); } - /** - * @see org.slf4j.Logger#warn(java.lang.String, java.lang.Object) - */ @Override public void warn(String format, Object arg) { log(null, WARN, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#warn(java.lang.String, java.lang.Object[]) - */ @Override public void warn(String format, Object[] argArray) { log(null, WARN, format, argArray, null); } - /** - * @see org.slf4j.Logger#warn(java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void warn(String format, Object arg1, Object arg2) { log(null, WARN, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#warn(java.lang.String, java.lang.Throwable) - */ @Override public void warn(String msg, Throwable t) { log(null, WARN, msg, null, t); } - /** - * @see org.slf4j.Logger#warn(org.slf4j.Marker, java.lang.String) - */ @Override public void warn(Marker marker, String msg) { log(marker, WARN, msg, null, null); } - /** - * @see org.slf4j.Logger#warn(org.slf4j.Marker, java.lang.String, java.lang.Object) - */ @Override public void warn(Marker marker, String format, Object arg) { log(marker, WARN, format, new Object[]{arg}, null); } - /** - * @see org.slf4j.Logger#warn(org.slf4j.Marker, java.lang.String, java.lang.Object, java.lang.Object) - */ @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { log(marker, WARN, format, new Object[]{arg1, arg2}, null); } - /** - * @see org.slf4j.Logger#warn(org.slf4j.Marker, java.lang.String, java.lang.Object[]) - */ @Override public void warn(Marker marker, String format, Object[] argArray) { log(marker, WARN, format, argArray, null); } - /** - * @see org.slf4j.Logger#warn(org.slf4j.Marker, java.lang.String, java.lang.Throwable) - */ @Override public void warn(Marker marker, String msg, Throwable t) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/AWTLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/AWTLeakPreventer.java index 15239db9b85..28c34da9250 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/AWTLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/AWTLeakPreventer.java @@ -32,9 +32,6 @@ import java.awt.Toolkit; public class AWTLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/DOMLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/DOMLeakPreventer.java index 62826fbcf68..f228536328c 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/DOMLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/DOMLeakPreventer.java @@ -34,9 +34,6 @@ import javax.xml.parsers.DocumentBuilderFactory; public class DOMLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/GCThreadLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/GCThreadLeakPreventer.java index 82404e26883..7743d0918da 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/GCThreadLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/GCThreadLeakPreventer.java @@ -38,9 +38,6 @@ import java.lang.reflect.Method; public class GCThreadLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/Java2DLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/Java2DLeakPreventer.java index 0a2ea5af26e..073bddf3e59 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/Java2DLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/Java2DLeakPreventer.java @@ -29,9 +29,6 @@ package org.eclipse.jetty.util.preventers; public class Java2DLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LDAPLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LDAPLeakPreventer.java index 7a1abfecbd8..696e603c913 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LDAPLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LDAPLeakPreventer.java @@ -31,9 +31,6 @@ package org.eclipse.jetty.util.preventers; public class LDAPLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LoginConfigurationLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LoginConfigurationLeakPreventer.java index 7d3698ab08e..567a3d55d49 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LoginConfigurationLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/LoginConfigurationLeakPreventer.java @@ -30,9 +30,6 @@ package org.eclipse.jetty.util.preventers; public class LoginConfigurationLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/SecurityProviderLeakPreventer.java b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/SecurityProviderLeakPreventer.java index 7be0a6da142..0f3752de27b 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/SecurityProviderLeakPreventer.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/preventers/SecurityProviderLeakPreventer.java @@ -32,9 +32,6 @@ import java.security.Security; public class SecurityProviderLeakPreventer extends AbstractLeakPreventer { - /** - * @see org.eclipse.jetty.util.preventers.AbstractLeakPreventer#prevent(java.lang.ClassLoader) - */ @Override public void prevent(ClassLoader loader) { diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java index aaa9c8f5600..9e7f78c089f 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebAppContext.java @@ -386,9 +386,6 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL return _resourceAliases.remove(alias); } - /* (non-Javadoc) - * @see org.eclipse.jetty.server.server.handler.ContextHandler#setClassLoader(java.lang.ClassLoader) - */ @Override public void setClassLoader(ClassLoader classLoader) { @@ -527,9 +524,6 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL _configurations.postConfigure(this); } - /* - * @see org.eclipse.thread.AbstractLifeCycle#doStart() - */ @Override protected void doStart() throws Exception { diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java index ed22a9413a0..ad19b2d4d11 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java @@ -99,9 +99,6 @@ public class WebInfConfiguration extends AbstractConfiguration context.setBaseResource(_preUnpackBaseResource); } - /** - * @see org.eclipse.jetty.webapp.AbstractConfiguration#cloneConfigure(org.eclipse.jetty.webapp.WebAppContext, org.eclipse.jetty.webapp.WebAppContext) - */ @Override public void cloneConfigure(WebAppContext template, WebAppContext context) throws Exception { diff --git a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/OrderingTest.java b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/OrderingTest.java index 276cddeaffa..c3b4c2ca853 100644 --- a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/OrderingTest.java +++ b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/OrderingTest.java @@ -51,45 +51,30 @@ public class OrderingTest _name = name; } - /** - * @see org.eclipse.jetty.util.resource.Resource#addPath(java.lang.String) - */ @Override public Resource addPath(String path) throws IOException, MalformedURLException { return null; } - /** - * @see org.eclipse.jetty.util.resource.Resource#delete() - */ @Override public boolean delete() throws SecurityException { return false; } - /** - * @see org.eclipse.jetty.util.resource.Resource#exists() - */ @Override public boolean exists() { return false; } - /** - * @see org.eclipse.jetty.util.resource.Resource#getFile() - */ @Override public File getFile() throws IOException { return null; } - /** - * @see org.eclipse.jetty.util.resource.Resource#getInputStream() - */ @Override public InputStream getInputStream() throws IOException { @@ -102,9 +87,6 @@ public class OrderingTest return null; } - /** - * @see org.eclipse.jetty.util.resource.Resource#getName() - */ @Override public String getName() { @@ -117,62 +99,41 @@ public class OrderingTest return null; } - /** - * @see org.eclipse.jetty.util.resource.Resource#isContainedIn(org.eclipse.jetty.util.resource.Resource) - */ @Override public boolean isContainedIn(Resource r) throws MalformedURLException { return false; } - /** - * @see org.eclipse.jetty.util.resource.Resource#isDirectory() - */ @Override public boolean isDirectory() { return false; } - /** - * @see org.eclipse.jetty.util.resource.Resource#lastModified() - */ @Override public long lastModified() { return 0; } - /** - * @see org.eclipse.jetty.util.resource.Resource#length() - */ @Override public long length() { return 0; } - /** - * @see org.eclipse.jetty.util.resource.Resource#list() - */ @Override public String[] list() { return null; } - /** - * @see org.eclipse.jetty.util.resource.Resource#close() - */ @Override public void close() { } - /** - * @see org.eclipse.jetty.util.resource.Resource#renameTo(org.eclipse.jetty.util.resource.Resource) - */ @Override public boolean renameTo(Resource dest) throws SecurityException { diff --git a/tests/test-distribution/src/main/java/org/eclipse/jetty/tests/distribution/DistributionTester.java b/tests/test-distribution/src/main/java/org/eclipse/jetty/tests/distribution/DistributionTester.java index 67f71c45559..1e2ea636175 100644 --- a/tests/test-distribution/src/main/java/org/eclipse/jetty/tests/distribution/DistributionTester.java +++ b/tests/test-distribution/src/main/java/org/eclipse/jetty/tests/distribution/DistributionTester.java @@ -479,9 +479,6 @@ public class DistributionTester consoleStreamers.forEach(ConsoleStreamer::stop); } - /** - * @see #destroy() - */ @Override public void close() { diff --git a/tests/test-integration/src/test/java/org/eclipse/jetty/test/DigestPostTest.java b/tests/test-integration/src/test/java/org/eclipse/jetty/test/DigestPostTest.java index 18f637188b3..930106598b9 100644 --- a/tests/test-integration/src/test/java/org/eclipse/jetty/test/DigestPostTest.java +++ b/tests/test-integration/src/test/java/org/eclipse/jetty/test/DigestPostTest.java @@ -100,18 +100,12 @@ public class DigestPostTest roles.put(username, rolenames); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadRoleInfo(org.eclipse.jetty.security.AbstractLoginService.UserPrincipal) - */ @Override protected String[] loadRoleInfo(UserPrincipal user) { return roles.get(user.getName()); } - /** - * @see org.eclipse.jetty.security.AbstractLoginService#loadUserInfo(java.lang.String) - */ @Override protected UserPrincipal loadUserInfo(String username) { diff --git a/tests/test-integration/src/test/java/org/eclipse/jetty/test/jsp/FakeJspServlet.java b/tests/test-integration/src/test/java/org/eclipse/jetty/test/jsp/FakeJspServlet.java index 7824a54ad0d..e8862320935 100644 --- a/tests/test-integration/src/test/java/org/eclipse/jetty/test/jsp/FakeJspServlet.java +++ b/tests/test-integration/src/test/java/org/eclipse/jetty/test/jsp/FakeJspServlet.java @@ -29,9 +29,6 @@ import javax.servlet.http.HttpServletResponse; public class FakeJspServlet extends HttpServlet { - /* - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { diff --git a/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java index 3bc59e1cadf..c42e7b71b87 100644 --- a/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java @@ -39,9 +39,6 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi FileTestHelper.teardown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/FileSessionDataStoreTest.java b/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/FileSessionDataStoreTest.java index 5e9751c61c6..86c2878d566 100644 --- a/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/FileSessionDataStoreTest.java +++ b/tests/test-sessions/test-file-sessions/src/test/java/org/eclipse/jetty/server/session/FileSessionDataStoreTest.java @@ -74,9 +74,6 @@ public class FileSessionDataStoreTest extends AbstractSessionDataStoreTest } } - /** - * - */ @Override public boolean checkSessionPersisted(SessionData data) throws Exception { diff --git a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredOrphanedSessionTest.java index 11769e7edd5..809b82ab1c5 100644 --- a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredOrphanedSessionTest.java @@ -46,9 +46,6 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi __testSupport.tearDown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredSessionScavengingTest.java b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredSessionScavengingTest.java index 881d34191e0..ea1e2ed8daa 100644 --- a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/ClusteredSessionScavengingTest.java @@ -45,9 +45,6 @@ public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScav __testSupport.tearDown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreTest.java b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreTest.java index 29d83f8338f..0023b85ffa5 100644 --- a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreTest.java +++ b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionDataStoreTest.java @@ -81,9 +81,6 @@ public class GCloudSessionDataStoreTest extends AbstractSessionDataStoreTest return __testSupport.checkSessionExists(data.getId()); } - /** - * - */ @Override public boolean checkSessionPersisted(SessionData data) throws Exception { diff --git a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTestSupport.java b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTestSupport.java index eb2d42a7047..661b57d150b 100644 --- a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTestSupport.java +++ b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/GCloudSessionTestSupport.java @@ -68,9 +68,6 @@ public class GCloudSessionTestSupport _d = d; } - /** - * @see org.eclipse.jetty.gcloud.session.GCloudSessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/InvalidationSessionTest.java b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/InvalidationSessionTest.java index c13287467bb..88b47832e4e 100644 --- a/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/InvalidationSessionTest.java +++ b/tests/test-sessions/test-gcloud-sessions/src/test/java/org/eclipse/jetty/gcloud/session/InvalidationSessionTest.java @@ -45,9 +45,6 @@ public class InvalidationSessionTest extends AbstractClusteredInvalidationSessio __testSupport.tearDown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredOrphanedSessionTest.java index 15d04fa5559..aac2b34ad52 100644 --- a/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredOrphanedSessionTest.java @@ -46,9 +46,6 @@ public class ClusteredOrphanedSessionTest _testHelper.tearDown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredSessionScavengingTest.java b/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredSessionScavengingTest.java index dfdcdbd52a5..620a044e8b8 100644 --- a/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-hazelcast-sessions/src/test/java/org/eclipse/jetty/hazelcast/session/ClusteredSessionScavengingTest.java @@ -46,9 +46,6 @@ public class ClusteredSessionScavengingTest _testHelper.tearDown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java index 26f85d65473..26b256a3e21 100644 --- a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java @@ -42,9 +42,6 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi __testSupport.teardown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java index 668c4284587..965962593fd 100644 --- a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java @@ -53,9 +53,6 @@ public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScav super.testClusteredScavenge(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredInvalidationSessionTest.java b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredInvalidationSessionTest.java index c1af0830fa9..61ccf05ed5b 100644 --- a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredInvalidationSessionTest.java +++ b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredInvalidationSessionTest.java @@ -45,9 +45,6 @@ public class RemoteClusteredInvalidationSessionTest extends AbstractClusteredInv __testSupport.teardown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredSessionScavengingTest.java b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredSessionScavengingTest.java index cb048c1f74b..d7ba530c638 100644 --- a/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-infinispan-sessions/src/test/java/org/eclipse/jetty/server/session/remote/RemoteClusteredSessionScavengingTest.java @@ -45,9 +45,6 @@ public class RemoteClusteredSessionScavengingTest extends AbstractClusteredSessi __testSupport.teardown(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredInvalidationSessionTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredInvalidationSessionTest.java index 69eda55dbc7..d81074084c1 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredInvalidationSessionTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredInvalidationSessionTest.java @@ -32,9 +32,6 @@ public class ClusteredInvalidationSessionTest extends AbstractClusteredInvalidat JdbcTestHelper.shutdown(null); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java index 2fe34944f49..7e0ee188959 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredOrphanedSessionTest.java @@ -25,9 +25,6 @@ import org.junit.jupiter.api.AfterEach; */ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessionTest { - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java index 0200800bccc..b3b8a0232e4 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionScavengingTest.java @@ -25,9 +25,6 @@ import org.junit.jupiter.api.AfterEach; */ public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScavengingTest { - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/SessionTableSchemaTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/SessionTableSchemaTest.java index 6a3bbc0e936..3c644ad2abb 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/SessionTableSchemaTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/SessionTableSchemaTest.java @@ -50,9 +50,6 @@ public class SessionTableSchemaTest _da = new DatabaseAdaptor() { - /** - * @see org.eclipse.jetty.server.session.DatabaseAdaptor#isEmptyStringNull() - */ @Override public boolean isEmptyStringNull() { diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/WebAppObjectInSessionTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/WebAppObjectInSessionTest.java index 276b1984f92..c3a2b12c3d4 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/WebAppObjectInSessionTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/WebAppObjectInSessionTest.java @@ -28,9 +28,6 @@ import org.junit.jupiter.api.Test; public class WebAppObjectInSessionTest extends AbstractWebAppObjectInSessionTest { - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/sessions/MemcachedTestHelper.java b/tests/test-sessions/test-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/sessions/MemcachedTestHelper.java index e9b5c21f6ab..bfe8a905044 100644 --- a/tests/test-sessions/test-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/sessions/MemcachedTestHelper.java +++ b/tests/test-sessions/test-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/sessions/MemcachedTestHelper.java @@ -122,9 +122,6 @@ public class MemcachedTestHelper public static class MockDataStoreFactory extends AbstractSessionDataStoreFactory { - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredInvalidateSessionTest.java b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredInvalidateSessionTest.java index 7d8047da2d8..8b2c0062d9f 100644 --- a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredInvalidateSessionTest.java +++ b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredInvalidateSessionTest.java @@ -39,9 +39,6 @@ public class ClusteredInvalidateSessionTest extends AbstractClusteredInvalidatio MongoTestHelper.dropCollection(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredOrphanedSessionTest.java b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredOrphanedSessionTest.java index 42b04a53630..fefbdea4ef8 100644 --- a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredOrphanedSessionTest.java @@ -43,9 +43,6 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi MongoTestHelper.dropCollection(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredSessionScavengingTest.java b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredSessionScavengingTest.java index fac13f9ff68..d841c48e8dc 100644 --- a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredSessionScavengingTest.java +++ b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/ClusteredSessionScavengingTest.java @@ -39,9 +39,6 @@ public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScav MongoTestHelper.dropCollection(); } - /** - * @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory() - */ @Override public SessionDataStoreFactory createSessionDataStoreFactory() { diff --git a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/TestSessionDataStoreFactory.java b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/TestSessionDataStoreFactory.java index eb2703083c6..30fcb71e995 100644 --- a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/TestSessionDataStoreFactory.java +++ b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/TestSessionDataStoreFactory.java @@ -24,9 +24,6 @@ package org.eclipse.jetty.server.session; public class TestSessionDataStoreFactory extends AbstractSessionDataStoreFactory { - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java index f0c8b72e2d0..b8aa43e5398 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java @@ -104,9 +104,6 @@ public class DeleteUnloadableSessionTest public static class DelSessionDataStoreFactory extends AbstractSessionDataStoreFactory { - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DirtyAttributeTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DirtyAttributeTest.java index 79bd4ebe05a..325cd51786b 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DirtyAttributeTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DirtyAttributeTest.java @@ -58,9 +58,6 @@ public class DirtyAttributeTest public class TestPassivatingSessionDataStore extends TestSessionDataStore { - /** - * @see org.eclipse.jetty.server.session.TestSessionDataStore#isPassivating() - */ @Override public boolean isPassivating() { @@ -71,9 +68,6 @@ public class DirtyAttributeTest public class TestPassivatingSessionDataStoreFactory extends AbstractSessionDataStoreFactory { - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { @@ -177,18 +171,12 @@ public class DirtyAttributeTest int binds = 0; int unbinds = 0; - /** - * @see javax.servlet.http.HttpSessionActivationListener#sessionWillPassivate(javax.servlet.http.HttpSessionEvent) - */ @Override public void sessionWillPassivate(HttpSessionEvent se) { ++passivates; } - /** - * @see javax.servlet.http.HttpSessionActivationListener#sessionDidActivate(javax.servlet.http.HttpSessionEvent) - */ @Override public void sessionDidActivate(HttpSessionEvent se) { @@ -215,18 +203,12 @@ public class DirtyAttributeTest assertEquals(expected, unbinds); } - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent) - */ @Override public void valueBound(HttpSessionBindingEvent event) { ++binds; } - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent) - */ @Override public void valueUnbound(HttpSessionBindingEvent event) { diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/SessionEvictionFailureTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/SessionEvictionFailureTest.java index 480424eb9f5..e602959df49 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/SessionEvictionFailureTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/SessionEvictionFailureTest.java @@ -112,9 +112,6 @@ public class SessionEvictionFailureTest _nextStoreResults = storeResults; } - /** - * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler) - */ @Override public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception { diff --git a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/TestFilter.java b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/TestFilter.java index 3d3a9def77c..cb215dbad7d 100644 --- a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/TestFilter.java +++ b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/TestFilter.java @@ -50,9 +50,6 @@ public class TestFilter implements Filter private ServletContext _context; private final Set _allowed = new HashSet(); - /* - * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) - */ @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -65,9 +62,6 @@ public class TestFilter implements Filter LOG.debug("TestFilter#remote=" + _remote); } - /* - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException @@ -113,9 +107,6 @@ public class TestFilter implements Filter } } - /* - * @see javax.servlet.Filter#destroy() - */ @Override public void destroy() { diff --git a/tests/test-webapps/test-jetty-webapp/src/test/java/org/eclipse/jetty/TestServer.java b/tests/test-webapps/test-jetty-webapp/src/test/java/org/eclipse/jetty/TestServer.java index 229a3b16914..9d34984b173 100644 --- a/tests/test-webapps/test-jetty-webapp/src/test/java/org/eclipse/jetty/TestServer.java +++ b/tests/test-webapps/test-jetty-webapp/src/test/java/org/eclipse/jetty/TestServer.java @@ -162,9 +162,6 @@ public class TestServer private static class RestartHandler extends HandlerWrapper { - /** - * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { diff --git a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockDataSource.java b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockDataSource.java index 8adf63c5444..7d16f9bce5f 100644 --- a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockDataSource.java +++ b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockDataSource.java @@ -39,18 +39,12 @@ public class MockDataSource implements DataSource return null; } - /** - * @see javax.sql.DataSource#getConnection() - */ @Override public Connection getConnection() throws SQLException { return null; } - /** - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) - */ @Override public Connection getConnection(String username, String password) throws SQLException @@ -58,35 +52,23 @@ public class MockDataSource implements DataSource return null; } - /** - * @see javax.sql.DataSource#getLogWriter() - */ @Override public PrintWriter getLogWriter() throws SQLException { return null; } - /** - * @see javax.sql.DataSource#getLoginTimeout() - */ @Override public int getLoginTimeout() throws SQLException { return 0; } - /** - * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) - */ @Override public void setLogWriter(PrintWriter out) throws SQLException { } - /** - * @see javax.sql.DataSource#setLoginTimeout(int) - */ @Override public void setLoginTimeout(int seconds) throws SQLException { diff --git a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockTransport.java b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockTransport.java index a3a4d0f3707..0b9fd2937d1 100644 --- a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockTransport.java +++ b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockTransport.java @@ -38,9 +38,6 @@ public class MockTransport extends Transport super(session, urlname); } - /** - * @see javax.mail.Transport#sendMessage(javax.mail.Message, javax.mail.Address[]) - */ @Override public void sendMessage(Message arg0, Address[] arg1) throws MessagingException { diff --git a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockUserTransaction.java b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockUserTransaction.java index d9b37c2afd5..edffcaf2957 100644 --- a/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockUserTransaction.java +++ b/tests/test-webapps/test-mock-resources/src/main/java/com/acme/MockUserTransaction.java @@ -31,17 +31,11 @@ import javax.transaction.UserTransaction; public class MockUserTransaction implements UserTransaction { - /** - * @see javax.transaction.UserTransaction#begin() - */ @Override public void begin() throws NotSupportedException, SystemException { } - /** - * @see javax.transaction.UserTransaction#commit() - */ @Override public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, @@ -49,35 +43,23 @@ public class MockUserTransaction implements UserTransaction { } - /** - * @see javax.transaction.UserTransaction#getStatus() - */ @Override public int getStatus() throws SystemException { return 0; } - /** - * @see javax.transaction.UserTransaction#rollback() - */ @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { } - /** - * @see javax.transaction.UserTransaction#setRollbackOnly() - */ @Override public void setRollbackOnly() throws IllegalStateException, SystemException { } - /** - * @see javax.transaction.UserTransaction#setTransactionTimeout(int) - */ @Override public void setTransactionTimeout(int arg0) throws SystemException { diff --git a/tests/test-webapps/test-servlet-spec/test-container-initializer/src/main/java/com/acme/initializer/FooInitializer.java b/tests/test-webapps/test-servlet-spec/test-container-initializer/src/main/java/com/acme/initializer/FooInitializer.java index 5f19fba7668..ca1751ad108 100644 --- a/tests/test-webapps/test-servlet-spec/test-container-initializer/src/main/java/com/acme/initializer/FooInitializer.java +++ b/tests/test-webapps/test-servlet-spec/test-container-initializer/src/main/java/com/acme/initializer/FooInitializer.java @@ -33,18 +33,12 @@ public class FooInitializer implements ServletContainerInitializer public static class BarListener implements ServletContextListener { - /** - * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) - */ @Override public void contextInitialized(ServletContextEvent sce) { throw new IllegalStateException("BAR LISTENER CALLED!"); } - /** - * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) - */ @Override public void contextDestroyed(ServletContextEvent sce) { @@ -55,9 +49,6 @@ public class FooInitializer implements ServletContainerInitializer public static class FooListener implements ServletContextListener { - /** - * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) - */ @Override public void contextInitialized(ServletContextEvent sce) { @@ -83,9 +74,6 @@ public class FooInitializer implements ServletContainerInitializer } } - /** - * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) - */ @Override public void contextDestroyed(ServletContextEvent sce) { diff --git a/tests/test-webapps/test-webapp-rfc2616/src/main/java/org/eclipse/jetty/tests/webapp/HttpMethodsServlet.java b/tests/test-webapps/test-webapp-rfc2616/src/main/java/org/eclipse/jetty/tests/webapp/HttpMethodsServlet.java index 98a1b4337a0..d7e1a290b82 100644 --- a/tests/test-webapps/test-webapp-rfc2616/src/main/java/org/eclipse/jetty/tests/webapp/HttpMethodsServlet.java +++ b/tests/test-webapps/test-webapp-rfc2616/src/main/java/org/eclipse/jetty/tests/webapp/HttpMethodsServlet.java @@ -43,56 +43,36 @@ public class HttpMethodsServlet extends HttpServlet super(); } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* do nothing */ } - /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse - * response) - */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* do nothing */ } - /** - * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) - */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* do nothing */ } - /** - * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse) - */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* do nothing */ } - /** - * @see HttpServlet#doHead(HttpServletRequest, HttpServletResponse) - */ @Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* do nothing */ } - /** - * @see HttpServlet#doTrace(HttpServletRequest, HttpServletResponse) - */ @Override protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { From 9d589f1b6e2b8cc09d5bf53ab00a68a74d7b7b3a Mon Sep 17 00:00:00 2001 From: olivier lamy Date: Tue, 18 Feb 2020 10:42:26 +1000 Subject: [PATCH 18/27] fix checkstyle issue Signed-off-by: olivier lamy --- .../org/eclipse/jetty/server/MultiPartFormInputStreamTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java index 9da8a15dc06..524885ee5b4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java @@ -26,10 +26,10 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collection; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.MultipartConfigElement; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; From f6195b39ea9227553f45a8bb32aca52c1b3a6a60 Mon Sep 17 00:00:00 2001 From: Lachlan Roberts Date: Tue, 18 Feb 2020 13:52:19 +1100 Subject: [PATCH 19/27] Issue #4581 - fix checkstyle errors Signed-off-by: Lachlan Roberts --- .../org/eclipse/jetty/server/MultiPartFormInputStreamTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java index 9da8a15dc06..524885ee5b4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/MultiPartFormInputStreamTest.java @@ -26,10 +26,10 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collection; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.MultipartConfigElement; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; From 5fe202f29f535fe964aa81dbed7fa3f644a07aef Mon Sep 17 00:00:00 2001 From: Lachlan Date: Tue, 18 Feb 2020 21:43:54 +1100 Subject: [PATCH 20/27] Issue #4548 - clean up websocket removing duplicated and unused classes (#4549) Create new module websocket-util which contains implementation classes shared by websocket-jetty and websocket-javax. Many of these classes had to be changed as the javax and jetty versions of them differed slightly. Also includes general cleanups, removed unused interfaces and classes, etc.. --- .../eclipse/jetty/osgi/test/TestOSGiUtil.java | 13 +- jetty-websocket/pom.xml | 1 + .../jetty/websocket/core/CoreSession.java | 12 + .../core/client/ClientUpgradeRequest.java | 2 +- .../core/internal/WebSocketCoreSession.java | 11 +- .../server/internal/AbstractHandshaker.java | 6 +- .../core/GeneratorFrameFlagsTest.java | 2 +- .../jetty/websocket/core/GeneratorTest.java | 3 +- .../jetty/websocket/core/ParserCapture.java | 2 +- .../core/extensions/ExtensionTool.java | 2 +- .../PerMessageDeflateExtensionTest.java | 2 +- .../websocket-javax-client/pom.xml | 5 + .../src/main/java/module-info.java | 3 +- .../client/AnnotatedClientEndpointConfig.java | 2 +- .../DelegatedJavaxClientUpgradeRequest.java | 52 -- .../DelegatedJavaxClientUpgradeResponse.java | 58 -- .../client/JavaxClientUpgradeRequest.java | 25 +- ...vaxWebSocketClientFrameHandlerFactory.java | 2 +- .../websocket-javax-common/pom.xml | 5 + .../src/main/java/module-info.java | 2 +- .../common/CompletableFutureCallback.java | 48 -- .../javax/common/DuplicateCoderException.java | 38 -- .../common/JavaxWebSocketAsyncRemote.java | 6 +- .../common/JavaxWebSocketBasicRemote.java | 2 +- .../common/JavaxWebSocketFrameHandler.java | 34 +- .../JavaxWebSocketFrameHandlerFactory.java | 59 +- .../JavaxWebSocketFrameHandlerMetadata.java | 2 + .../common/JavaxWebSocketRemoteEndpoint.java | 8 +- .../javax/common/JavaxWebSocketSession.java | 2 +- .../common/JavaxWebSocketUpgradeRequest.java | 34 -- .../common/JavaxWebSocketUpgradeResponse.java | 30 - .../websocket/javax/common/MessageSink.java | 37 -- .../javax/common/UpgradeRequestAdapter.java | 3 +- .../javax/common/UpgradeResponse.java | 30 - .../javax/common/UpgradeResponseAdapter.java | 63 -- .../common/decoders/AvailableDecoders.java | 6 +- .../javax/common/decoders/BooleanDecoder.java | 6 +- .../common/encoders/AvailableEncoders.java | 11 +- .../messages/ByteBufferMessageSink.java | 90 --- .../messages/DecodedBinaryMessageSink.java | 9 +- .../DecodedBinaryStreamMessageSink.java | 9 +- .../common/messages/DecodedMessageSink.java | 9 +- .../messages/DecodedTextMessageSink.java | 9 +- .../DecodedTextStreamMessageSink.java | 9 +- .../javax/common/messages/MessageReader.java | 48 -- .../util/DuplicateAnnotationException.java | 56 -- .../javax/common/util/ReflectUtils.java | 562 ------------------ .../websocket/javax/common/util/TextUtil.java | 97 --- .../common/DummyFrameHandlerFactory.java | 2 +- ...ebSocketFrameHandlerBadSignaturesTest.java | 2 +- ...SocketFrameHandlerOnMessageBinaryTest.java | 2 +- ...ebSocketFrameHandlerOnMessageTextTest.java | 2 +- .../DecodedBinaryMessageSinkTest.java | 14 +- .../DecodedBinaryStreamMessageSinkTest.java | 14 +- .../messages/DecodedTextMessageSinkTest.java | 14 +- .../DecodedTextStreamMessageSinkTest.java | 14 +- .../messages/InputStreamMessageSinkTest.java | 31 +- .../common/messages/MessageWriterTest.java | 19 +- .../messages/ReaderMessageSinkTest.java | 15 +- .../util/InvokerUtilsStaticParamsTest.java | 14 +- .../javax/common/util/InvokerUtilsTest.java | 53 +- .../common/util/NameParamIdentifier.java | 1 + .../javax/common/util/ReflectUtilsTest.java | 1 + .../main/config/modules/websocket-javax.mod | 1 + ...st.java => JavaxServerUpgradeRequest.java} | 4 +- ...vaxWebSocketServerFrameHandlerFactory.java | 2 +- .../server/internal/PathParamIdentifier.java | 2 +- .../internal/UpgradeResponseAdapter.java | 47 -- .../tests/CompletableFutureMethodHandle.java | 7 +- .../tests/matchers/IsMessageHandlerType.java | 2 +- .../tests/client/MessageReceivingTest.java | 2 +- .../tests/coders/AvailableDecodersTest.java | 2 +- .../tests/coders/AvailableEncodersTest.java | 2 +- .../tests/coders/DecoderTextStreamTest.java | 12 +- .../tests/server/DeploymentExceptionTest.java | 2 +- .../websocket-jetty-common/pom.xml | 5 + .../src/main/java/module-info.java | 4 +- .../websocket/common/AbstractMessageSink.java | 34 -- .../common/CompletableFutureCallback.java | 48 -- .../common/FunctionCallException.java | 51 -- .../common/JettyWebSocketFrameHandler.java | 20 +- .../JettyWebSocketFrameHandlerFactory.java | 128 ++-- .../JettyWebSocketFrameHandlerMetadata.java | 1 + .../invoke/InvalidSignatureException.java | 72 --- .../websocket/common/invoke/InvokerUtils.java | 369 ------------ .../common/message/ByteArrayMessageSink.java | 105 ---- .../common/message/CallbackBuffer.java | 42 -- .../common/message/DispatchedMessageSink.java | 176 ------ .../message/InputStreamMessageSink.java | 40 -- .../common/message/MessageInputStream.java | 227 ------- .../common/message/MessageOutputStream.java | 218 ------- .../common/message/MessageWriter.java | 222 ------- .../message/PartialBinaryMessageSink.java | 48 -- .../message/PartialTextMessageSink.java | 59 -- .../common/message/ReaderMessageSink.java | 39 -- .../common/message/StringMessageSink.java | 105 ---- .../websocket/common/util/Utf8CharBuffer.java | 117 ---- ...tty.websocket.common.reflect.ArgIdentifier | 1 - .../common/LocalEndpointMetadataTest.java | 16 +- .../common/MessageInputStreamTest.java | 2 +- .../common/MessageOutputStreamTest.java | 9 +- .../websocket/common/MessageWriterTest.java | 9 +- .../common/OutgoingMessageCapture.java | 180 +----- .../annotated/AnnotatedBinaryArraySocket.java | 2 +- .../AnnotatedBinaryStreamSocket.java | 2 +- .../annotated/AnnotatedTextSocket.java | 2 +- .../annotated/AnnotatedTextStreamSocket.java | 2 +- .../listeners/ListenerBasicSocket.java | 2 +- .../listeners/ListenerFrameSocket.java | 2 +- .../listeners/ListenerPartialSocket.java | 2 +- .../listeners/ListenerPingPongSocket.java | 2 +- .../common/handshake/DummyUpgradeRequest.java | 205 ------- .../handshake/DummyUpgradeResponse.java | 108 ---- .../common/invoke/InvokerUtilsTest.java | 54 +- .../common/invoke/NameParamIdentifier.java | 3 +- .../common/util/Utf8CharBufferTest.java | 126 ---- .../main/config/modules/websocket-jetty.mod | 1 + .../jetty/websocket/tests/ErrorCloseTest.java | 15 +- .../tests/client/ClientCloseTest.java | 2 +- .../tests/server/PartialListenerTest.java | 2 +- .../websocket/servlet/WebSocketMapping.java | 6 +- jetty-websocket/websocket-util/pom.xml | 60 ++ .../src/main/java/module-info.java} | 10 +- .../util/DuplicateAnnotationException.java | 4 +- .../util/InvalidSignatureException.java | 4 +- .../util}/InvalidWebSocketException.java | 2 +- .../jetty/websocket}/util/InvokerUtils.java | 47 +- .../jetty/websocket}/util/ReflectUtils.java | 4 +- .../jetty/websocket}/util/TextUtil.java | 2 +- .../util}/messages/AbstractMessageSink.java | 11 +- .../util}/messages/ByteArrayMessageSink.java | 22 +- .../util/messages}/ByteBufferMessageSink.java | 25 +- .../util}/messages/CallbackBuffer.java | 2 +- .../util}/messages/DispatchedMessageSink.java | 16 +- .../messages/InputStreamMessageSink.java | 7 +- .../util}/messages/MessageInputStream.java | 3 +- .../util}/messages/MessageOutputStream.java | 64 +- .../util/messages}/MessageReader.java | 3 +- .../websocket/util/messages}/MessageSink.java | 2 +- .../util}/messages/MessageWriter.java | 9 +- .../messages/PartialByteArrayMessageSink.java | 11 +- .../PartialByteBufferMessageSink.java | 14 +- .../messages/PartialStringMessageSink.java | 6 +- .../util}/messages/ReaderMessageSink.java | 6 +- .../util}/messages/StringMessageSink.java | 13 +- .../test/resources/jetty-logging.properties | 1 + 146 files changed, 657 insertions(+), 4386 deletions(-) delete mode 100644 jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeRequest.java delete mode 100644 jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeResponse.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/CompletableFutureCallback.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/DuplicateCoderException.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeRequest.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeResponse.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/MessageSink.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponse.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponseAdapter.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteBufferMessageSink.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageReader.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/DuplicateAnnotationException.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtils.java delete mode 100644 jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/TextUtil.java rename jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/{DelegatedJavaxServletUpgradeRequest.java => JavaxServerUpgradeRequest.java} (89%) delete mode 100644 jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/UpgradeResponseAdapter.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/AbstractMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/CompletableFutureCallback.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/FunctionCallException.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvalidSignatureException.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtils.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteArrayMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/CallbackBuffer.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/DispatchedMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/InputStreamMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageInputStream.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageOutputStream.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageWriter.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialBinaryMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialTextMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ReaderMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/StringMessageSink.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/Utf8CharBuffer.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/main/resources/META-INF/services/org.eclipse.jetty.websocket.common.reflect.ArgIdentifier delete mode 100644 jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeRequest.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeResponse.java delete mode 100644 jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/util/Utf8CharBufferTest.java create mode 100644 jetty-websocket/websocket-util/pom.xml rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/package-info.java => websocket-util/src/main/java/module-info.java} (78%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common => websocket-util/src/main/java/org/eclipse/jetty/websocket}/util/DuplicateAnnotationException.java (93%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket}/util/InvalidSignatureException.java (94%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/InvalidWebSocketException.java (96%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket}/util/InvokerUtils.java (89%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common => websocket-util/src/main/java/org/eclipse/jetty/websocket}/util/ReflectUtils.java (99%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common => websocket-util/src/main/java/org/eclipse/jetty/websocket}/util/TextUtil.java (98%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/AbstractMessageSink.java (71%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/ByteArrayMessageSink.java (80%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message => websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages}/ByteBufferMessageSink.java (77%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/CallbackBuffer.java (95%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/DispatchedMessageSink.java (91%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/InputStreamMessageSink.java (79%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/MessageInputStream.java (98%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/MessageOutputStream.java (77%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message => websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages}/MessageReader.java (93%) rename jetty-websocket/{websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages}/MessageSink.java (96%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/MessageWriter.java (95%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/PartialByteArrayMessageSink.java (84%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/PartialByteBufferMessageSink.java (79%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/PartialStringMessageSink.java (93%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/ReaderMessageSink.java (83%) rename jetty-websocket/{websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common => websocket-util/src/main/java/org/eclipse/jetty/websocket/util}/messages/StringMessageSink.java (84%) create mode 100644 jetty-websocket/websocket-util/src/test/resources/jetty-logging.properties diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java index 6f17c5dd81e..ba0aa680755 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java @@ -147,16 +147,17 @@ public class TestOSGiUtil res.add(mavenBundle().groupId("org.eclipse.jetty").artifactId("jetty-plus").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty").artifactId("jetty-annotations").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-core").versionAsInProject().start()); - res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-api").versionAsInProject().start()); - res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-common").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-servlet").versionAsInProject().start()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-util").versionAsInProject().start()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-api").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-server").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-client").versionAsInProject().start()); - - res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-common").versionAsInProject().noStart()); - res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-client").versionAsInProject().noStart()); - res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-server").versionAsInProject().noStart()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-jetty-common").versionAsInProject().start()); res.add(mavenBundle().groupId("org.eclipse.jetty.toolchain").artifactId("jetty-javax-websocket-api").versionAsInProject().noStart()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-server").versionAsInProject().noStart()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-client").versionAsInProject().noStart()); + res.add(mavenBundle().groupId("org.eclipse.jetty.websocket").artifactId("websocket-javax-common").versionAsInProject().noStart()); + res.add(mavenBundle().groupId("org.eclipse.jetty.osgi").artifactId("jetty-osgi-boot").versionAsInProject().start()); return res; } diff --git a/jetty-websocket/pom.xml b/jetty-websocket/pom.xml index ef53e976f33..b2952f150a8 100644 --- a/jetty-websocket/pom.xml +++ b/jetty-websocket/pom.xml @@ -16,6 +16,7 @@ websocket-core websocket-servlet + websocket-util websocket-jetty-api websocket-jetty-common diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/CoreSession.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/CoreSession.java index 977d07ad4f9..8f298677a6d 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/CoreSession.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/CoreSession.java @@ -81,6 +81,12 @@ public interface CoreSession extends OutgoingFrames, Configuration */ Behavior getBehavior(); + /** + * TODO + * @return + */ + WebSocketComponents getWebSocketComponents(); + /** * @return The shared ByteBufferPool */ @@ -214,6 +220,12 @@ public interface CoreSession extends OutgoingFrames, Configuration return null; } + @Override + public WebSocketComponents getWebSocketComponents() + { + return null; + } + @Override public ByteBufferPool getByteBufferPool() { diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/ClientUpgradeRequest.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/ClientUpgradeRequest.java index 2ca5886da7f..4678bddb420 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/ClientUpgradeRequest.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/ClientUpgradeRequest.java @@ -425,7 +425,7 @@ public abstract class ClientUpgradeRequest extends HttpRequest implements Respon extensionStack, WebSocketConstants.SPEC_VERSION_STRING); - WebSocketCoreSession coreSession = new WebSocketCoreSession(frameHandler, Behavior.CLIENT, negotiated); + WebSocketCoreSession coreSession = new WebSocketCoreSession(frameHandler, Behavior.CLIENT, negotiated, wsClient.getWebSocketComponents()); customizer.customize(coreSession); HttpClient httpClient = wsClient.getHttpClient(); diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketCoreSession.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketCoreSession.java index 3cf6ceeb0ba..18d9b079c76 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketCoreSession.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketCoreSession.java @@ -45,6 +45,7 @@ import org.eclipse.jetty.websocket.core.FrameHandler; import org.eclipse.jetty.websocket.core.IncomingFrames; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.core.OutgoingFrames; +import org.eclipse.jetty.websocket.core.WebSocketComponents; import org.eclipse.jetty.websocket.core.WebSocketConstants; import org.eclipse.jetty.websocket.core.exception.CloseException; import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; @@ -63,6 +64,7 @@ public class WebSocketCoreSession implements IncomingFrames, CoreSession, Dumpab private static final Logger LOG = Log.getLogger(WebSocketCoreSession.class); private static final CloseStatus NO_CODE = new CloseStatus(CloseStatus.NO_CODE); + private final WebSocketComponents components; private final Behavior behavior; private final WebSocketSessionState sessionState = new WebSocketSessionState(); private final FrameHandler handler; @@ -81,8 +83,9 @@ public class WebSocketCoreSession implements IncomingFrames, CoreSession, Dumpab private Duration writeTimeout = WebSocketConstants.DEFAULT_WRITE_TIMEOUT; private final ContextHandler contextHandler; - public WebSocketCoreSession(FrameHandler handler, Behavior behavior, Negotiated negotiated) + public WebSocketCoreSession(FrameHandler handler, Behavior behavior, Negotiated negotiated, WebSocketComponents components) { + this.components = components; this.handler = handler; this.behavior = behavior; this.negotiated = negotiated; @@ -794,6 +797,12 @@ public class WebSocketCoreSession implements IncomingFrames, CoreSession, Dumpab return behavior; } + @Override + public WebSocketComponents getWebSocketComponents() + { + return components; + } + @Override public String toString() { diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/server/internal/AbstractHandshaker.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/server/internal/AbstractHandshaker.java index 69ac06b895f..7946371e847 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/server/internal/AbstractHandshaker.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/server/internal/AbstractHandshaker.java @@ -137,7 +137,7 @@ public abstract class AbstractHandshaker implements Handshaker Negotiated negotiated = new Negotiated(baseRequest.getHttpURI().toURI(), protocol, baseRequest.isSecure(), extensionStack, WebSocketConstants.SPEC_VERSION_STRING); // Create the Session - WebSocketCoreSession coreSession = newWebSocketCoreSession(handler, negotiated); + WebSocketCoreSession coreSession = newWebSocketCoreSession(handler, negotiated, components); if (defaultCustomizer != null) defaultCustomizer.customize(coreSession); negotiator.customize(coreSession); @@ -200,9 +200,9 @@ public abstract class AbstractHandshaker implements Handshaker return true; } - protected WebSocketCoreSession newWebSocketCoreSession(FrameHandler handler, Negotiated negotiated) + protected WebSocketCoreSession newWebSocketCoreSession(FrameHandler handler, Negotiated negotiated, WebSocketComponents components) { - return new WebSocketCoreSession(handler, Behavior.SERVER, negotiated); + return new WebSocketCoreSession(handler, Behavior.SERVER, negotiated, components); } protected abstract WebSocketConnection createWebSocketConnection(Request baseRequest, WebSocketCoreSession coreSession); diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorFrameFlagsTest.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorFrameFlagsTest.java index 6e7e344d349..af413ce7ea7 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorFrameFlagsTest.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorFrameFlagsTest.java @@ -64,7 +64,7 @@ public class GeneratorFrameFlagsTest { ExtensionStack exStack = new ExtensionStack(components, Behavior.SERVER); exStack.negotiate(new LinkedList<>(), new LinkedList<>()); - this.coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.CLIENT, Negotiated.from(exStack)); + this.coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.CLIENT, Negotiated.from(exStack), components); } @ParameterizedTest diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorTest.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorTest.java index 55fa88a3d13..51e0c0a1400 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorTest.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/GeneratorTest.java @@ -49,13 +49,14 @@ public class GeneratorTest private static Generator generator = new Generator(); private static WebSocketCoreSession coreSession = newWebSocketCoreSession(Behavior.SERVER); + private static WebSocketComponents components = new WebSocketComponents(); private static WebSocketCoreSession newWebSocketCoreSession(Behavior behavior) { WebSocketComponents components = new WebSocketComponents(); ExtensionStack exStack = new ExtensionStack(components, Behavior.SERVER); exStack.negotiate(new LinkedList<>(), new LinkedList<>()); - return new WebSocketCoreSession(new TestMessageHandler(), behavior, Negotiated.from(exStack)); + return new WebSocketCoreSession(new TestMessageHandler(), behavior, Negotiated.from(exStack), components); } /** diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/ParserCapture.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/ParserCapture.java index bd8270b5e28..b69e6800135 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/ParserCapture.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/ParserCapture.java @@ -56,7 +56,7 @@ public class ParserCapture WebSocketComponents components = new WebSocketComponents(); ExtensionStack exStack = new ExtensionStack(components, Behavior.SERVER); exStack.negotiate(new LinkedList<>(), new LinkedList<>()); - this.coreSession = new WebSocketCoreSession(new TestMessageHandler(), behavior, Negotiated.from(exStack)); + this.coreSession = new WebSocketCoreSession(new TestMessageHandler(), behavior, Negotiated.from(exStack), components); coreSession.setAutoFragment(false); coreSession.setMaxFrameSize(0); this.parser = new Parser(components.getBufferPool(), coreSession); diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/ExtensionTool.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/ExtensionTool.java index c6ee2bf1083..c8d080b0a13 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/ExtensionTool.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/ExtensionTool.java @@ -166,7 +166,7 @@ public class ExtensionTool { ExtensionStack exStack = new ExtensionStack(components, Behavior.SERVER); exStack.negotiate(new LinkedList<>(), new LinkedList<>()); - WebSocketCoreSession coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.SERVER, Negotiated.from(exStack)); + WebSocketCoreSession coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.SERVER, Negotiated.from(exStack), components); return coreSession; } } diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/PerMessageDeflateExtensionTest.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/PerMessageDeflateExtensionTest.java index 22d881d9996..50c814d6a1c 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/PerMessageDeflateExtensionTest.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/extensions/PerMessageDeflateExtensionTest.java @@ -605,7 +605,7 @@ public class PerMessageDeflateExtensionTest extends AbstractExtensionTest ExtensionStack exStack = new ExtensionStack(components, Behavior.SERVER); exStack.negotiate(new LinkedList<>(), new LinkedList<>()); - WebSocketCoreSession coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.SERVER, Negotiated.from(exStack)); + WebSocketCoreSession coreSession = new WebSocketCoreSession(new TestMessageHandler(), Behavior.SERVER, Negotiated.from(exStack), components); configuration.customize(configuration); return coreSession; } diff --git a/jetty-websocket/websocket-javax-client/pom.xml b/jetty-websocket/websocket-javax-client/pom.xml index 4d682c19865..b2fa1cd48aa 100644 --- a/jetty-websocket/websocket-javax-client/pom.xml +++ b/jetty-websocket/websocket-javax-client/pom.xml @@ -15,6 +15,11 @@ + + org.eclipse.jetty.websocket + websocket-util + ${project.version} + org.eclipse.jetty.websocket websocket-javax-common diff --git a/jetty-websocket/websocket-javax-client/src/main/java/module-info.java b/jetty-websocket/websocket-javax-client/src/main/java/module-info.java index deeac7152d0..c3e34017719 100644 --- a/jetty-websocket/websocket-javax-client/src/main/java/module-info.java +++ b/jetty-websocket/websocket-javax-client/src/main/java/module-info.java @@ -25,8 +25,9 @@ module org.eclipse.jetty.websocket.javax.client exports org.eclipse.jetty.websocket.javax.client; requires transitive org.eclipse.jetty.client; - requires org.eclipse.jetty.websocket.core; requires transitive org.eclipse.jetty.websocket.javax.common; + requires org.eclipse.jetty.websocket.core; + requires org.eclipse.jetty.websocket.util; provides ContainerProvider with JavaxWebSocketClientContainerProvider; } diff --git a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/AnnotatedClientEndpointConfig.java b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/AnnotatedClientEndpointConfig.java index bcc389f39c9..fc91b3c413f 100644 --- a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/AnnotatedClientEndpointConfig.java +++ b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/AnnotatedClientEndpointConfig.java @@ -24,7 +24,7 @@ import javax.websocket.ClientEndpoint; import javax.websocket.ClientEndpointConfig; import org.eclipse.jetty.websocket.javax.common.ClientEndpointConfigWrapper; -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; public class AnnotatedClientEndpointConfig extends ClientEndpointConfigWrapper { diff --git a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeRequest.java b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeRequest.java deleted file mode 100644 index d98b88f142f..00000000000 --- a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeRequest.java +++ /dev/null @@ -1,52 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.client; - -import java.net.URI; -import java.security.Principal; - -import org.eclipse.jetty.websocket.core.client.ClientUpgradeRequest; -import org.eclipse.jetty.websocket.javax.common.UpgradeRequest; - -/** - * Representing the Jetty {@link org.eclipse.jetty.client.HttpClient}'s {@link org.eclipse.jetty.client.HttpRequest} - * in the {@link UpgradeRequest} interface. - */ -public class DelegatedJavaxClientUpgradeRequest implements UpgradeRequest -{ - private final ClientUpgradeRequest delegate; - - public DelegatedJavaxClientUpgradeRequest(ClientUpgradeRequest delegate) - { - this.delegate = delegate; - } - - @Override - public Principal getUserPrincipal() - { - // User Principal not available from Client API - return null; - } - - @Override - public URI getRequestURI() - { - return delegate.getURI(); - } -} diff --git a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeResponse.java b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeResponse.java deleted file mode 100644 index a7a63fac531..00000000000 --- a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/DelegatedJavaxClientUpgradeResponse.java +++ /dev/null @@ -1,58 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.client; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.eclipse.jetty.client.HttpResponse; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.websocket.core.ExtensionConfig; -import org.eclipse.jetty.websocket.javax.common.UpgradeResponse; - -/** - * Representing the Jetty {@link org.eclipse.jetty.client.HttpClient}'s {@link HttpResponse} - * in the {@link UpgradeResponse} interface. - */ -public class DelegatedJavaxClientUpgradeResponse implements UpgradeResponse -{ - private HttpResponse delegate; - - public DelegatedJavaxClientUpgradeResponse(HttpResponse response) - { - this.delegate = response; - } - - @Override - public String getAcceptedSubProtocol() - { - return this.delegate.getHeaders().get(HttpHeader.SEC_WEBSOCKET_SUBPROTOCOL); - } - - @Override - public List getExtensions() - { - List rawExtensions = delegate.getHeaders().getValuesList(HttpHeader.SEC_WEBSOCKET_EXTENSIONS); - if (rawExtensions == null || rawExtensions.isEmpty()) - return Collections.emptyList(); - - return rawExtensions.stream().map((parameterizedName) -> ExtensionConfig.parse(parameterizedName)).collect(Collectors.toList()); - } -} diff --git a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxClientUpgradeRequest.java b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxClientUpgradeRequest.java index e4e53df2f00..5541724164b 100644 --- a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxClientUpgradeRequest.java +++ b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxClientUpgradeRequest.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.websocket.javax.client; import java.net.URI; +import java.security.Principal; import org.eclipse.jetty.client.HttpResponse; import org.eclipse.jetty.io.EndPoint; @@ -28,25 +29,20 @@ import org.eclipse.jetty.websocket.core.client.WebSocketCoreClient; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandler; import org.eclipse.jetty.websocket.javax.common.UpgradeRequest; -public class JavaxClientUpgradeRequest extends ClientUpgradeRequest +public class JavaxClientUpgradeRequest extends ClientUpgradeRequest implements UpgradeRequest { - private final JavaxWebSocketClientContainer containerContext; private final JavaxWebSocketFrameHandler frameHandler; public JavaxClientUpgradeRequest(JavaxWebSocketClientContainer clientContainer, WebSocketCoreClient coreClient, URI requestURI, Object websocketPojo) { super(coreClient, requestURI); - this.containerContext = clientContainer; - - UpgradeRequest upgradeRequest = new DelegatedJavaxClientUpgradeRequest(this); - frameHandler = containerContext.newFrameHandler(websocketPojo, upgradeRequest); + frameHandler = clientContainer.newFrameHandler(websocketPojo, this); } @Override public void upgrade(HttpResponse response, EndPoint endPoint) { - frameHandler.setUpgradeRequest(new DelegatedJavaxClientUpgradeRequest(this)); - frameHandler.setUpgradeResponse(new DelegatedJavaxClientUpgradeResponse(response)); + frameHandler.setUpgradeRequest(this); super.upgrade(response, endPoint); } @@ -55,4 +51,17 @@ public class JavaxClientUpgradeRequest extends ClientUpgradeRequest { return frameHandler; } + + @Override + public Principal getUserPrincipal() + { + // User Principal not available from Client API + return null; + } + + @Override + public URI getRequestURI() + { + return getURI(); + } } diff --git a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxWebSocketClientFrameHandlerFactory.java b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxWebSocketClientFrameHandlerFactory.java index c434f6bff3c..3eac9cb84fc 100644 --- a/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxWebSocketClientFrameHandlerFactory.java +++ b/jetty-websocket/websocket-javax-client/src/main/java/org/eclipse/jetty/websocket/javax/client/JavaxWebSocketClientFrameHandlerFactory.java @@ -25,7 +25,7 @@ import javax.websocket.EndpointConfig; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketContainer; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerFactory; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerMetadata; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; public class JavaxWebSocketClientFrameHandlerFactory extends JavaxWebSocketFrameHandlerFactory { diff --git a/jetty-websocket/websocket-javax-common/pom.xml b/jetty-websocket/websocket-javax-common/pom.xml index 012853b1462..26688bbf644 100644 --- a/jetty-websocket/websocket-javax-common/pom.xml +++ b/jetty-websocket/websocket-javax-common/pom.xml @@ -71,6 +71,11 @@ websocket-core ${project.version} + + org.eclipse.jetty.websocket + websocket-util + ${project.version} + org.eclipse.jetty.toolchain jetty-javax-websocket-api diff --git a/jetty-websocket/websocket-javax-common/src/main/java/module-info.java b/jetty-websocket/websocket-javax-common/src/main/java/module-info.java index c7f22e28552..89d937226be 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/module-info.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/module-info.java @@ -22,10 +22,10 @@ module org.eclipse.jetty.websocket.javax.common exports org.eclipse.jetty.websocket.javax.common.decoders; exports org.eclipse.jetty.websocket.javax.common.encoders; exports org.eclipse.jetty.websocket.javax.common.messages; - exports org.eclipse.jetty.websocket.javax.common.util; requires transitive jetty.websocket.api; requires transitive org.eclipse.jetty.http; requires transitive org.eclipse.jetty.io; requires transitive org.eclipse.jetty.websocket.core; + requires transitive org.eclipse.jetty.websocket.util; } diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/CompletableFutureCallback.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/CompletableFutureCallback.java deleted file mode 100644 index 3b0380896c3..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/CompletableFutureCallback.java +++ /dev/null @@ -1,48 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import java.util.concurrent.CompletableFuture; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - -public class CompletableFutureCallback extends CompletableFuture implements Callback -{ - private static final Logger LOG = Log.getLogger(CompletableFutureCallback.class); - - @Override - public void failed(Throwable cause) - { - if (LOG.isDebugEnabled()) - LOG.debug("failed()", cause); - - completeExceptionally(cause); - } - - @Override - public void succeeded() - { - if (LOG.isDebugEnabled()) - LOG.debug("succeeded()"); - - complete(this); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/DuplicateCoderException.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/DuplicateCoderException.java deleted file mode 100644 index c24cc45a526..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/DuplicateCoderException.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -/** - * Thrown when a duplicate coder is encountered when attempting to identify a Endpoint's metadata ({@link javax.websocket.Decoder} or {@link javax.websocket.Encoder}) - * TODO: is this still needed? - */ -public class DuplicateCoderException extends InvalidWebSocketException -{ - private static final long serialVersionUID = -3049181444035417170L; - - public DuplicateCoderException(String message) - { - super(message); - } - - public DuplicateCoderException(String message, Throwable cause) - { - super(message, cause); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketAsyncRemote.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketAsyncRemote.java index 1b6f9f66493..c38a6af7176 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketAsyncRemote.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketAsyncRemote.java @@ -33,9 +33,9 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.messages.MessageOutputStream; -import org.eclipse.jetty.websocket.javax.common.messages.MessageWriter; -import org.eclipse.jetty.websocket.javax.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; +import org.eclipse.jetty.websocket.util.messages.MessageOutputStream; +import org.eclipse.jetty.websocket.util.messages.MessageWriter; public class JavaxWebSocketAsyncRemote extends JavaxWebSocketRemoteEndpoint implements javax.websocket.RemoteEndpoint.Async { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketBasicRemote.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketBasicRemote.java index df234182085..53c02f78083 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketBasicRemote.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketBasicRemote.java @@ -33,7 +33,7 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; import static java.nio.charset.StandardCharsets.UTF_8; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java index fcb36ecad36..911ed9f824e 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java @@ -52,10 +52,11 @@ import org.eclipse.jetty.websocket.javax.common.messages.DecodedBinaryMessageSin import org.eclipse.jetty.websocket.javax.common.messages.DecodedBinaryStreamMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedTextMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedTextStreamMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialByteArrayMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialByteBufferMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialStringMessageSink; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.messages.MessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialByteArrayMessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialStringMessageSink; public class JavaxWebSocketFrameHandler implements FrameHandler { @@ -99,7 +100,6 @@ public class JavaxWebSocketFrameHandler implements FrameHandler private MethodHandle pongHandle; private UpgradeRequest upgradeRequest; - private UpgradeResponse upgradeResponse; private EndpointConfig endpointConfig; private final Map messageHandlerMap = new HashMap<>(); @@ -383,7 +383,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler if (byte[].class.isAssignableFrom(clazz)) { assertBasicTypeNotRegistered(OpCode.BINARY, this.binaryMetadata, handler.getClass().getName()); - MessageSink messageSink = new PartialByteArrayMessageSink(session, partialMessageHandler); + MessageSink messageSink = new PartialByteArrayMessageSink(coreSession, partialMessageHandler); this.binarySink = registerMessageHandler(OpCode.BINARY, clazz, handler, messageSink); JavaxWebSocketFrameHandlerMetadata.MessageMetadata metadata = new JavaxWebSocketFrameHandlerMetadata.MessageMetadata(); metadata.handle = partialMessageHandler; @@ -393,7 +393,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler else if (ByteBuffer.class.isAssignableFrom(clazz)) { assertBasicTypeNotRegistered(OpCode.BINARY, this.binaryMetadata, handler.getClass().getName()); - MessageSink messageSink = new PartialByteBufferMessageSink(session, partialMessageHandler); + MessageSink messageSink = new PartialByteBufferMessageSink(coreSession, partialMessageHandler); this.binarySink = registerMessageHandler(OpCode.BINARY, clazz, handler, messageSink); JavaxWebSocketFrameHandlerMetadata.MessageMetadata metadata = new JavaxWebSocketFrameHandlerMetadata.MessageMetadata(); metadata.handle = partialMessageHandler; @@ -403,7 +403,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler else if (String.class.isAssignableFrom(clazz)) { assertBasicTypeNotRegistered(OpCode.TEXT, this.textMetadata, handler.getClass().getName()); - MessageSink messageSink = new PartialStringMessageSink(session, partialMessageHandler); + MessageSink messageSink = new PartialStringMessageSink(coreSession, partialMessageHandler); this.textSink = registerMessageHandler(OpCode.TEXT, clazz, handler, messageSink); JavaxWebSocketFrameHandlerMetadata.MessageMetadata metadata = new JavaxWebSocketFrameHandlerMetadata.MessageMetadata(); metadata.handle = partialMessageHandler; @@ -460,7 +460,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { assertBasicTypeNotRegistered(OpCode.BINARY, this.binaryMetadata, handler.getClass().getName()); Decoder.Binary decoder = availableDecoders.getInstanceOf(registeredDecoder); - MessageSink messageSink = new DecodedBinaryMessageSink(session, decoder, wholeMsgMethodHandle); + MessageSink messageSink = new DecodedBinaryMessageSink(coreSession, decoder, wholeMsgMethodHandle); metadata.sinkClass = messageSink.getClass(); this.binarySink = registerMessageHandler(OpCode.BINARY, clazz, handler, messageSink); this.binaryMetadata = metadata; @@ -469,7 +469,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { assertBasicTypeNotRegistered(OpCode.BINARY, this.binaryMetadata, handler.getClass().getName()); Decoder.BinaryStream decoder = availableDecoders.getInstanceOf(registeredDecoder); - MessageSink messageSink = new DecodedBinaryStreamMessageSink(session, decoder, wholeMsgMethodHandle); + MessageSink messageSink = new DecodedBinaryStreamMessageSink(coreSession, decoder, wholeMsgMethodHandle); metadata.sinkClass = messageSink.getClass(); this.binarySink = registerMessageHandler(OpCode.BINARY, clazz, handler, messageSink); this.binaryMetadata = metadata; @@ -478,7 +478,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { assertBasicTypeNotRegistered(OpCode.TEXT, this.textMetadata, handler.getClass().getName()); Decoder.Text decoder = availableDecoders.getInstanceOf(registeredDecoder); - MessageSink messageSink = new DecodedTextMessageSink(session, decoder, wholeMsgMethodHandle); + MessageSink messageSink = new DecodedTextMessageSink(coreSession, decoder, wholeMsgMethodHandle); metadata.sinkClass = messageSink.getClass(); this.textSink = registerMessageHandler(OpCode.TEXT, clazz, handler, messageSink); this.textMetadata = metadata; @@ -487,7 +487,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { assertBasicTypeNotRegistered(OpCode.TEXT, this.textMetadata, handler.getClass().getName()); Decoder.TextStream decoder = availableDecoders.getInstanceOf(registeredDecoder); - MessageSink messageSink = new DecodedTextStreamMessageSink(session, decoder, wholeMsgMethodHandle); + MessageSink messageSink = new DecodedTextStreamMessageSink(coreSession, decoder, wholeMsgMethodHandle); metadata.sinkClass = messageSink.getClass(); this.textSink = registerMessageHandler(OpCode.TEXT, clazz, handler, messageSink); this.textMetadata = metadata; @@ -659,21 +659,11 @@ public class JavaxWebSocketFrameHandler implements FrameHandler this.upgradeRequest = upgradeRequest; } - public void setUpgradeResponse(UpgradeResponse upgradeResponse) - { - this.upgradeResponse = upgradeResponse; - } - public UpgradeRequest getUpgradeRequest() { return upgradeRequest; } - public UpgradeResponse getUpgradeResponse() - { - return upgradeResponse; - } - private void configListener(String key, Object value) { if (!key.startsWith("org.eclipse.jetty.websocket.")) diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerFactory.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerFactory.java index 1653877f2fe..f32209acf9c 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerFactory.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerFactory.java @@ -43,23 +43,26 @@ import javax.websocket.PongMessage; import javax.websocket.Session; import org.eclipse.jetty.http.pathmap.UriTemplatePathSpec; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.javax.common.decoders.AvailableDecoders; -import org.eclipse.jetty.websocket.javax.common.messages.ByteArrayMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.ByteBufferMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedBinaryMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedBinaryStreamMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedTextMessageSink; import org.eclipse.jetty.websocket.javax.common.messages.DecodedTextStreamMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.InputStreamMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialByteArrayMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialByteBufferMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.PartialStringMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.ReaderMessageSink; -import org.eclipse.jetty.websocket.javax.common.messages.StringMessageSink; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; -import org.eclipse.jetty.websocket.javax.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.messages.ByteArrayMessageSink; +import org.eclipse.jetty.websocket.util.messages.ByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.InputStreamMessageSink; +import org.eclipse.jetty.websocket.util.messages.MessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialByteArrayMessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialStringMessageSink; +import org.eclipse.jetty.websocket.util.messages.ReaderMessageSink; +import org.eclipse.jetty.websocket.util.messages.StringMessageSink; import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerMetadata.MessageMetadata; @@ -322,15 +325,15 @@ public abstract class JavaxWebSocketFrameHandlerFactory if (DecodedMessageSink.class.isAssignableFrom(msgMetadata.sinkClass)) { MethodHandle ctorHandle = MethodHandles.lookup().findConstructor(msgMetadata.sinkClass, - MethodType.methodType(void.class, JavaxWebSocketSession.class, msgMetadata.registeredDecoder.interfaceType, MethodHandle.class)); + MethodType.methodType(void.class, CoreSession.class, msgMetadata.registeredDecoder.interfaceType, MethodHandle.class)); Decoder decoder = session.getDecoders().getInstanceOf(msgMetadata.registeredDecoder); - return (MessageSink)ctorHandle.invoke(session, decoder, msgMetadata.handle); + return (MessageSink)ctorHandle.invoke(session.getCoreSession(), decoder, msgMetadata.handle); } else { MethodHandle ctorHandle = MethodHandles.lookup().findConstructor(msgMetadata.sinkClass, - MethodType.methodType(void.class, JavaxWebSocketSession.class, MethodHandle.class)); - return (MessageSink)ctorHandle.invoke(session, msgMetadata.handle); + MethodType.methodType(void.class, CoreSession.class, MethodHandle.class)); + return (MessageSink)ctorHandle.invoke(session.getCoreSession(), msgMetadata.handle); } } catch (NoSuchMethodException e) @@ -385,8 +388,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory protected JavaxWebSocketFrameHandlerMetadata createEndpointMetadata(Class endpointClass, EndpointConfig endpointConfig) { JavaxWebSocketFrameHandlerMetadata metadata = new JavaxWebSocketFrameHandlerMetadata(endpointConfig); - - MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodHandles.Lookup lookup = getMethodHandleLookup(endpointClass); Method openMethod = ReflectUtils.findMethod(endpointClass, "onOpen", javax.websocket.Session.class, javax.websocket.EndpointConfig.class); @@ -408,6 +410,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory protected JavaxWebSocketFrameHandlerMetadata discoverJavaxFrameHandlerMetadata(Class endpointClass, JavaxWebSocketFrameHandlerMetadata metadata) { + MethodHandles.Lookup lookup = getMethodHandleLookup(endpointClass); Method onmethod; // OnOpen [0..1] @@ -418,7 +421,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg ENDPOINT_CONFIG = new InvokerUtils.Arg(EndpointConfig.class); MethodHandle methodHandle = InvokerUtils - .mutatedInvoker(endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, ENDPOINT_CONFIG); + .mutatedInvoker(lookup, endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, ENDPOINT_CONFIG); metadata.setOpenHandler(methodHandle, onmethod); } @@ -430,7 +433,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg CLOSE_REASON = new InvokerUtils.Arg(CloseReason.class); MethodHandle methodHandle = InvokerUtils - .mutatedInvoker(endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, CLOSE_REASON); + .mutatedInvoker(lookup, endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, CLOSE_REASON); metadata.setCloseHandler(methodHandle, onmethod); } @@ -442,7 +445,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg CAUSE = new InvokerUtils.Arg(Throwable.class).required(); MethodHandle methodHandle = InvokerUtils - .mutatedInvoker(endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, CAUSE); + .mutatedInvoker(lookup, endpointClass, onmethod, paramIdentifier, metadata.getNamedTemplateVariables(), SESSION, CAUSE); metadata.setErrorHandler(methodHandle, onmethod); } @@ -465,7 +468,7 @@ public abstract class JavaxWebSocketFrameHandlerFactory // Function to search for matching MethodHandle for the endpointClass given a signature. Function getMethodHandle = (signature) -> - InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, paramIdentifier, metadata.getNamedTemplateVariables(), signature); + InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, paramIdentifier, metadata.getNamedTemplateVariables(), signature); // Try to match from available decoders. if (matchDecoders(onMsg, metadata, msgMetadata, getMethodHandle)) @@ -701,6 +704,20 @@ public abstract class JavaxWebSocketFrameHandlerFactory } } + private MethodHandles.Lookup getMethodHandleLookup(Class endpointClass) throws InvalidWebSocketException + { + MethodHandles.Lookup lookup; + try + { + lookup = MethodHandles.privateLookupIn(endpointClass, MethodHandles.lookup()); + } + catch (IllegalAccessException e) + { + throw new InvalidWebSocketException("Unable to obtain MethodHandle lookup for " + endpointClass, e); + } + return lookup; + } + private static class DecodedArgs { public final AvailableDecoders.RegisteredDecoder registeredDecoder; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerMetadata.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerMetadata.java index e417a7f5b09..b5db28e9969 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerMetadata.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerMetadata.java @@ -26,6 +26,8 @@ import javax.websocket.EndpointConfig; import org.eclipse.jetty.http.pathmap.UriTemplatePathSpec; import org.eclipse.jetty.websocket.javax.common.decoders.AvailableDecoders; import org.eclipse.jetty.websocket.javax.common.encoders.AvailableEncoders; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; +import org.eclipse.jetty.websocket.util.messages.MessageSink; public class JavaxWebSocketFrameHandlerMetadata { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketRemoteEndpoint.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketRemoteEndpoint.java index 93d7260734c..9f541a0e83c 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketRemoteEndpoint.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketRemoteEndpoint.java @@ -36,8 +36,8 @@ import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.core.OutgoingFrames; import org.eclipse.jetty.websocket.core.exception.WebSocketException; -import org.eclipse.jetty.websocket.javax.common.messages.MessageOutputStream; -import org.eclipse.jetty.websocket.javax.common.messages.MessageWriter; +import org.eclipse.jetty.websocket.util.messages.MessageOutputStream; +import org.eclipse.jetty.websocket.util.messages.MessageWriter; public class JavaxWebSocketRemoteEndpoint implements javax.websocket.RemoteEndpoint, OutgoingFrames { @@ -56,12 +56,12 @@ public class JavaxWebSocketRemoteEndpoint implements javax.websocket.RemoteEndpo protected MessageWriter newMessageWriter() { - return new MessageWriter(coreSession, coreSession.getOutputBufferSize()); + return new MessageWriter(coreSession, session.getContainerImpl().getBufferPool()); } protected MessageOutputStream newMessageOutputStream() { - return new MessageOutputStream(coreSession, coreSession.getOutputBufferSize(), session.getContainerImpl().getBufferPool()); + return new MessageOutputStream(coreSession, session.getContainerImpl().getBufferPool()); } @Override diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java index 8576dbbb1a3..2c7377c37ee 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java @@ -46,7 +46,7 @@ import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.ExtensionConfig; import org.eclipse.jetty.websocket.javax.common.decoders.AvailableDecoders; import org.eclipse.jetty.websocket.javax.common.encoders.AvailableEncoders; -import org.eclipse.jetty.websocket.javax.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; /** * Client Session for the JSR. diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeRequest.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeRequest.java deleted file mode 100644 index b8e4d634405..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeRequest.java +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import java.net.URI; -import java.util.List; -import java.util.Map; - -public interface JavaxWebSocketUpgradeRequest -{ - boolean isSecure(); - - Map> getParameterMap(); - - String getProtocolVersion(); - - URI getRequestURI(); -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeResponse.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeResponse.java deleted file mode 100644 index aa481b029d3..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketUpgradeResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import java.util.List; - -import org.eclipse.jetty.websocket.core.ExtensionConfig; - -public interface JavaxWebSocketUpgradeResponse -{ - String getAcceptedSubProtocol(); - - List getExtensions(); -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/MessageSink.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/MessageSink.java deleted file mode 100644 index f7a9bc8033a..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/MessageSink.java +++ /dev/null @@ -1,37 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.core.Frame; - -/** - * Sink consumer for messages (used for multiple frames with continuations, - * and also to allow for streaming APIs) - */ -public interface MessageSink -{ - /** - * Consume the frame payload to the message. - * - * @param frame the frame, its payload (and fin state) to append - * @param callback the callback for how the frame was consumed - */ - void accept(Frame frame, Callback callback); -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeRequestAdapter.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeRequestAdapter.java index b36e7d88f03..4ab2345d669 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeRequestAdapter.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeRequestAdapter.java @@ -23,11 +23,12 @@ import java.security.Principal; public class UpgradeRequestAdapter implements UpgradeRequest { - private URI requestURI; + private final URI requestURI; public UpgradeRequestAdapter() { /* anonymous, no requestURI, upgrade request */ + this(null); } public UpgradeRequestAdapter(URI uri) diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponse.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponse.java deleted file mode 100644 index 600e6f89596..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import java.util.List; - -import org.eclipse.jetty.websocket.core.ExtensionConfig; - -public interface UpgradeResponse -{ - String getAcceptedSubProtocol(); - - List getExtensions(); -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponseAdapter.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponseAdapter.java deleted file mode 100644 index 5cae4f9566e..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/UpgradeResponseAdapter.java +++ /dev/null @@ -1,63 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common; - -import java.util.Collections; -import java.util.List; - -import org.eclipse.jetty.websocket.core.ExtensionConfig; - -public class UpgradeResponseAdapter implements UpgradeResponse -{ - private final String acceptedSubProtocol; - private final List extensions; - - public UpgradeResponseAdapter() - { - this(null, Collections.emptyList()); - } - - public UpgradeResponseAdapter(String acceptedSubProtocol, List extensions) - { - this.acceptedSubProtocol = acceptedSubProtocol; - this.extensions = extensions; - } - - /** - * Get the accepted WebSocket protocol. - * - * @return the accepted WebSocket protocol. - */ - @Override - public String getAcceptedSubProtocol() - { - return acceptedSubProtocol; - } - - /** - * Get the list of extensions that should be used for the websocket. - * - * @return the list of negotiated extensions to use. - */ - @Override - public List getExtensions() - { - return extensions; - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/AvailableDecoders.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/AvailableDecoders.java index 5ec094c52a0..51703c57824 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/AvailableDecoders.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/AvailableDecoders.java @@ -32,9 +32,9 @@ import javax.websocket.Decoder; import javax.websocket.EndpointConfig; import org.eclipse.jetty.websocket.javax.common.InitException; -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; -import org.eclipse.jetty.websocket.javax.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; +import org.eclipse.jetty.websocket.util.ReflectUtils; public class AvailableDecoders implements Iterable { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/BooleanDecoder.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/BooleanDecoder.java index fef6ab1dd44..89e3f69ab44 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/BooleanDecoder.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/decoders/BooleanDecoder.java @@ -39,10 +39,6 @@ public class BooleanDecoder extends AbstractDecoder implements Decoder.Text> { @@ -289,9 +289,6 @@ public class AvailableEncoders implements Predicate> @Override public boolean test(Class type) { - return registeredEncoders.stream() - .filter(registered -> registered.isType(type)) - .findFirst() - .isPresent(); + return registeredEncoders.stream().anyMatch(registered -> registered.isType(type)); } } diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteBufferMessageSink.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteBufferMessageSink.java deleted file mode 100644 index 7aa73055533..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteBufferMessageSink.java +++ /dev/null @@ -1,90 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common.messages; - -import java.io.ByteArrayOutputStream; -import java.lang.invoke.MethodHandle; -import java.nio.ByteBuffer; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; - -public class ByteBufferMessageSink extends AbstractMessageSink -{ - private static final int BUFFER_SIZE = 65535; - private ByteArrayOutputStream out; - private int size; - - public ByteBufferMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) - { - super(session, methodHandle); - } - - @SuppressWarnings("Duplicates") - @Override - public void accept(Frame frame, Callback callback) - { - try - { - if (frame.hasPayload()) - { - ByteBuffer payload = frame.getPayload(); - - size += payload.remaining(); - if (session.getMaxBinaryMessageBufferSize() > 0 && size > session.getMaxBinaryMessageBufferSize()) - { - throw new MessageTooLargeException(String.format("Binary message too large: (actual) %,d > (configured max binary buffer size) %,d", - size, session.getMaxBinaryMessageBufferSize())); - } - - if (out == null) - out = new ByteArrayOutputStream(BUFFER_SIZE); - - BufferUtil.writeTo(payload, out); - payload.position(payload.limit()); // consume buffer - } - - if (frame.isFin()) - { - if (out != null) - methodHandle.invoke(ByteBuffer.wrap(out.toByteArray())); - else - methodHandle.invoke(BufferUtil.EMPTY_BUFFER); - } - - callback.succeeded(); - } - catch (Throwable t) - { - callback.failed(t); - } - finally - { - if (frame.isFin()) - { - // reset - out = null; - size = 0; - } - } - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSink.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSink.java index 9f9d38baf2b..dae52a2e198 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSink.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSink.java @@ -26,13 +26,14 @@ import javax.websocket.CloseReason; import javax.websocket.DecodeException; import javax.websocket.Decoder; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.exception.CloseException; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.MessageSink; +import org.eclipse.jetty.websocket.util.messages.ByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.MessageSink; public class DecodedBinaryMessageSink extends DecodedMessageSink> { - public DecodedBinaryMessageSink(JavaxWebSocketSession session, + public DecodedBinaryMessageSink(CoreSession session, Decoder.Binary decoder, MethodHandle methodHandle) throws NoSuchMethodException, IllegalAccessException @@ -49,7 +50,7 @@ public class DecodedBinaryMessageSink extends DecodedMessageSink extends DecodedMessageSink> { - public DecodedBinaryStreamMessageSink(JavaxWebSocketSession session, + public DecodedBinaryStreamMessageSink(CoreSession session, Decoder.BinaryStream decoder, MethodHandle methodHandle) throws NoSuchMethodException, IllegalAccessException @@ -49,7 +50,7 @@ public class DecodedBinaryStreamMessageSink extends DecodedMessageSink extends AbstractMessageSink { @@ -35,7 +36,7 @@ public abstract class DecodedMessageSink extends AbstractMess private final MethodHandle rawMethodHandle; private final MessageSink rawMessageSink; - public DecodedMessageSink(JavaxWebSocketSession session, T decoder, MethodHandle methodHandle) + public DecodedMessageSink(CoreSession session, T decoder, MethodHandle methodHandle) throws NoSuchMethodException, IllegalAccessException { super(session, methodHandle); @@ -48,7 +49,7 @@ public abstract class DecodedMessageSink extends AbstractMess protected abstract MethodHandle newRawMethodHandle() throws NoSuchMethodException, IllegalAccessException; - protected abstract MessageSink newRawMessageSink(JavaxWebSocketSession session, MethodHandle rawMethodHandle); + protected abstract MessageSink newRawMessageSink(CoreSession session, MethodHandle rawMethodHandle); public T getDecoder() { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSink.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSink.java index 58ce8ff3665..69c6f3005d7 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSink.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSink.java @@ -25,13 +25,14 @@ import javax.websocket.CloseReason; import javax.websocket.DecodeException; import javax.websocket.Decoder; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.exception.CloseException; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.MessageSink; +import org.eclipse.jetty.websocket.util.messages.MessageSink; +import org.eclipse.jetty.websocket.util.messages.StringMessageSink; public class DecodedTextMessageSink extends DecodedMessageSink> { - public DecodedTextMessageSink(JavaxWebSocketSession session, + public DecodedTextMessageSink(CoreSession session, Decoder.Text decoder, MethodHandle methodHandle) throws NoSuchMethodException, IllegalAccessException @@ -48,7 +49,7 @@ public class DecodedTextMessageSink extends DecodedMessageSink extends DecodedMessageSink> { - public DecodedTextStreamMessageSink(JavaxWebSocketSession session, + public DecodedTextStreamMessageSink(CoreSession session, Decoder.TextStream decoder, MethodHandle methodHandle) throws NoSuchMethodException, IllegalAccessException @@ -49,7 +50,7 @@ public class DecodedTextStreamMessageSink extends DecodedMessageSink - * In compliance to the WebSocket spec, this reader always uses the {@link StandardCharsets#UTF_8}. - */ -public class MessageReader extends InputStreamReader implements MessageSink -{ - private final MessageInputStream stream; - - public MessageReader(MessageInputStream stream) - { - super(stream, StandardCharsets.UTF_8); - this.stream = stream; - } - - @Override - public void accept(Frame frame, Callback callback) - { - this.stream.accept(frame, callback); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/DuplicateAnnotationException.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/DuplicateAnnotationException.java deleted file mode 100644 index 43223314ff3..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/DuplicateAnnotationException.java +++ /dev/null @@ -1,56 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common.util; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; - -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; - -@SuppressWarnings("serial") -public class DuplicateAnnotationException extends InvalidWebSocketException -{ - public static DuplicateAnnotationException build(Class pojo, Class annoClass, Method... methods) - { - // Build big detailed exception to help the developer - StringBuilder err = new StringBuilder(); - err.append("Duplicate @"); - err.append(annoClass.getSimpleName()); - err.append(" declarations in: "); - err.append(pojo.getName()); - - for (Method method : methods) - { - err.append(System.lineSeparator()); - ReflectUtils.append(err, method); - } - - return new DuplicateAnnotationException(err.toString()); - } - - public DuplicateAnnotationException(String message) - { - super(message); - } - - public DuplicateAnnotationException(String message, Throwable cause) - { - super(message, cause); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtils.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtils.java deleted file mode 100644 index a8942c615d7..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtils.java +++ /dev/null @@ -1,562 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common.util; - -import java.lang.annotation.Annotation; -import java.lang.invoke.MethodType; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; - -public class ReflectUtils -{ - - private static final Pattern JAVAX_CLASSNAME_PATTERN = Pattern.compile("^javax*\\..*"); - - private static class GenericRef - { - // The base class reference lookup started from - private final Class baseClass; - // The interface that we are interested in - private final Class ifaceClass; - - // The actual class generic interface was found on - Class genericClass; - - // The found genericType - public Type genericType; - private int genericIndex; - - public GenericRef(final Class baseClass, final Class ifaceClass) - { - this.baseClass = baseClass; - this.ifaceClass = ifaceClass; - } - - public boolean needsUnwrap() - { - return (genericClass == null) && (genericType != null) && (genericType instanceof TypeVariable); - } - - public void setGenericFromType(Type type, int index) - { - // debug("setGenericFromType(%s,%d)",toShortName(type),index); - this.genericType = type; - this.genericIndex = index; - if (type instanceof Class) - { - this.genericClass = (Class)type; - } - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("GenericRef [baseClass="); - builder.append(baseClass); - builder.append(", ifaceClass="); - builder.append(ifaceClass); - builder.append(", genericType="); - builder.append(genericType); - builder.append(", genericClass="); - builder.append(genericClass); - builder.append("]"); - return builder.toString(); - } - } - - private static StringBuilder appendTypeName(StringBuilder sb, Type type, boolean ellipses) - { - if (type instanceof Class) - { - Class ctype = (Class)type; - if (ctype.isArray()) - { - try - { - int dimensions = 0; - while (ctype.isArray()) - { - dimensions++; - ctype = ctype.getComponentType(); - } - sb.append(ctype.getName()); - for (int i = 0; i < dimensions; i++) - { - if (ellipses) - { - sb.append("..."); - } - else - { - sb.append("[]"); - } - } - return sb; - } - catch (Throwable ignore) - { - // ignore - } - } - - sb.append(ctype.getName()); - } - else - { - sb.append(type.toString()); - } - - return sb; - } - - public static void assertIsAnnotated(Method method, Class annoClass) - { - if (method.getAnnotation(annoClass) == null) - { - StringBuilder err = new StringBuilder(); - err.append("Method does not declare required @"); - err.append(annoClass.getName()); - err.append(" annotation: "); - err.append(method); - - throw new InvalidWebSocketException(err.toString()); - } - } - - public static void assertIsPublicNonStatic(Method method) - { - int mods = method.getModifiers(); - if (!Modifier.isPublic(mods)) - { - StringBuilder err = new StringBuilder(); - err.append("Invalid declaration of "); - err.append(method); - err.append(System.lineSeparator()); - - err.append("Method modifier must be public"); - - throw new InvalidWebSocketException(err.toString()); - } - - if (Modifier.isStatic(mods)) - { - StringBuilder err = new StringBuilder(); - err.append("Invalid declaration of "); - err.append(method); - err.append(System.lineSeparator()); - - err.append("Method modifier must not be static"); - - throw new InvalidWebSocketException(err.toString()); - } - } - - public static void assertIsReturn(Method method, Class type) - { - if (!type.equals(method.getReturnType())) - { - StringBuilder err = new StringBuilder(); - err.append("Invalid declaration of "); - err.append(method); - err.append(System.lineSeparator()); - - err.append("Return type must be ").append(type); - - throw new InvalidWebSocketException(err.toString()); - } - } - - public static Method findMethod(Class pojo, String methodName, Class... params) - { - try - { - return pojo.getMethod(methodName, params); - } - catch (NoSuchMethodException e) - { - return null; - } - } - - public static Method findAnnotatedMethod(Class pojo, Class anno) - { - Method[] methods = findAnnotatedMethods(pojo, anno); - if (methods == null) - { - return null; - } - - if (methods.length > 1) - { - throw DuplicateAnnotationException.build(pojo, anno, methods); - } - - return methods[0]; - } - - public static Method[] findAnnotatedMethods(Class pojo, Class anno) - { - List methods = null; - Class clazz = pojo; - - while ((clazz != null) && Object.class.isAssignableFrom(clazz)) - { - for (Method method : clazz.getDeclaredMethods()) - { - if (method.getAnnotation(anno) != null) - { - if (methods == null) - methods = new ArrayList<>(); - methods.add(method); - } - } - clazz = clazz.getSuperclass(); - } - - if (methods == null) - return null; - int len = methods.size(); - return methods.toArray(new Method[len]); - } - - /** - * Given a Base (concrete) Class, find the interface specified, and return its concrete Generic class declaration. - * - * @param baseClass the base (concrete) class to look in - * @param ifaceClass the interface of interest - * @return the (concrete) generic class that the interface exposes - */ - public static Class findGenericClassFor(Class baseClass, Class ifaceClass) - { - GenericRef ref = new GenericRef(baseClass, ifaceClass); - if (resolveGenericRef(ref, baseClass)) - { - // debug("Generic Found: %s",ref.genericClass); - return ref.genericClass; - } - - // debug("Generic not found: %s",ref); - return null; - } - - private static int findTypeParameterIndex(Class clazz, TypeVariable needVar) - { - // debug("findTypeParameterIndex(%s, [%s])",toShortName(clazz),toShortName(needVar)); - TypeVariable[] params = clazz.getTypeParameters(); - for (int i = 0; i < params.length; i++) - { - if (params[i].getName().equals(needVar.getName())) - { - // debug("Type Parameter found at index: [%d]",i); - return i; - } - } - // debug("Type Parameter NOT found"); - return -1; - } - - public static boolean isDefaultConstructable(Class clazz) - { - int mods = clazz.getModifiers(); - if (Modifier.isAbstract(mods) || !Modifier.isPublic(mods)) - { - // Needs to be public, non-abstract - return false; - } - - Class[] noargs = new Class[0]; - try - { - // Needs to have a no-args constructor - Constructor constructor = clazz.getConstructor(noargs); - // Constructor needs to be public - return Modifier.isPublic(constructor.getModifiers()); - } - catch (NoSuchMethodException | SecurityException e) - { - return false; - } - } - - public static boolean isSameParameters(Class[] actual, Class[] params) - { - if (actual.length != params.length) - { - // skip - return false; - } - - int len = params.length; - for (int i = 0; i < len; i++) - { - if (!actual[i].equals(params[i])) - { - return false; // not valid - } - } - - return true; - } - - private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) - { - if (type instanceof Class) - { - if (type == ref.ifaceClass) - { - // is this a straight ref or a TypeVariable? - // debug("Found ref (as class): %s",toShortName(type)); - ref.setGenericFromType(type, 0); - return true; - } - else - { - // Keep digging - return resolveGenericRef(ref, type); - } - } - - if (type instanceof ParameterizedType) - { - ParameterizedType ptype = (ParameterizedType)type; - Type rawType = ptype.getRawType(); - if (rawType == ref.ifaceClass) - { - // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); - // Always get the raw type parameter, let unwrap() solve for what it is - ref.setGenericFromType(ptype.getActualTypeArguments()[0], 0); - return true; - } - else - { - // Keep digging - return resolveGenericRef(ref, rawType); - } - } - return false; - } - - private static boolean resolveGenericRef(GenericRef ref, Type type) - { - if ((type == null) || (type == Object.class)) - { - return false; - } - - if (type instanceof Class) - { - Class clazz = (Class)type; - // prevent spinning off into Serialization and other parts of the - // standard tree that we could care less about - if (JAVAX_CLASSNAME_PATTERN.matcher(clazz.getName()).matches()) - { - return false; - } - - Type[] ifaces = clazz.getGenericInterfaces(); - for (Type iface : ifaces) - { - // debug("resolve %s interface[]: %s",toShortName(clazz),toShortName(iface)); - if (resolveGenericRef(ref, clazz, iface)) - { - if (ref.needsUnwrap()) - { - // debug("## Unwrap class %s::%s",toShortName(clazz),toShortName(iface)); - TypeVariable needVar = (TypeVariable)ref.genericType; - // debug("needs unwrap of type var [%s] - index [%d]",toShortName(needVar),ref.genericIndex); - - // attempt to find typeParameter on class itself - int typeParamIdx = findTypeParameterIndex(clazz, needVar); - // debug("type param index for %s[%s] is [%d]",toShortName(clazz),toShortName(needVar),typeParamIdx); - - if (typeParamIdx >= 0) - { - // found a type parameter, use it - // debug("unwrap from class [%s] - typeParameters[%d]",toShortName(clazz),typeParamIdx); - TypeVariable[] params = clazz.getTypeParameters(); - if (params.length >= typeParamIdx) - { - ref.setGenericFromType(params[typeParamIdx], typeParamIdx); - } - } - else if (iface instanceof ParameterizedType) - { - // use actual args on interface - Type arg = ((ParameterizedType)iface).getActualTypeArguments()[ref.genericIndex]; - ref.setGenericFromType(arg, ref.genericIndex); - } - } - return true; - } - } - - type = clazz.getGenericSuperclass(); - return resolveGenericRef(ref, type); - } - - if (type instanceof ParameterizedType) - { - ParameterizedType ptype = (ParameterizedType)type; - Class rawClass = (Class)ptype.getRawType(); - if (resolveGenericRef(ref, rawClass)) - { - if (ref.needsUnwrap()) - { - // debug("## Unwrap ParameterizedType %s::%s",toShortName(type),toShortName(rawClass)); - TypeVariable needVar = (TypeVariable)ref.genericType; - // debug("needs unwrap of type var [%s] - index [%d]",toShortName(needVar),ref.genericIndex); - int typeParamIdx = findTypeParameterIndex(rawClass, needVar); - // debug("type paramIdx of %s::%s is index [%d]",toShortName(rawClass),toShortName(needVar),typeParamIdx); - - Type arg = ptype.getActualTypeArguments()[typeParamIdx]; - ref.setGenericFromType(arg, typeParamIdx); - return true; - } - } - } - - return false; - } - - public static String toShortName(Type type) - { - if (type == null) - { - return ""; - } - - if (type instanceof Class) - { - String name = ((Class)type).getName(); - return trimClassName(name); - } - - if (type instanceof ParameterizedType) - { - ParameterizedType ptype = (ParameterizedType)type; - StringBuilder str = new StringBuilder(); - str.append(trimClassName(((Class)ptype.getRawType()).getName())); - str.append("<"); - Type[] args = ptype.getActualTypeArguments(); - for (int i = 0; i < args.length; i++) - { - if (i > 0) - { - str.append(","); - } - str.append(args[i]); - } - str.append(">"); - return str.toString(); - } - - return type.toString(); - } - - public static String toString(Class pojo, Method method) - { - StringBuilder str = new StringBuilder(); - - append(str, pojo, method); - - return str.toString(); - } - - public static String trimClassName(String name) - { - int idx = name.lastIndexOf('.'); - name = name.substring(idx + 1); - idx = name.lastIndexOf('$'); - if (idx >= 0) - { - name = name.substring(idx + 1); - } - return name; - } - - public static void append(StringBuilder str, Class pojo, Method method) - { - // method modifiers - int mod = method.getModifiers() & Modifier.methodModifiers(); - if (mod != 0) - { - str.append(Modifier.toString(mod)).append(' '); - } - - // return type - Type retType = method.getGenericReturnType(); - appendTypeName(str, retType, false).append(' '); - - if (pojo != null) - { - // class name - str.append(pojo.getName()); - str.append("#"); - } - - // method name - str.append(method.getName()); - - // method parameters - str.append('('); - Type[] params = method.getGenericParameterTypes(); - for (int j = 0; j < params.length; j++) - { - boolean ellipses = method.isVarArgs() && (j == (params.length - 1)); - appendTypeName(str, params[j], ellipses); - if (j < (params.length - 1)) - { - str.append(", "); - } - } - str.append(')'); - - // TODO: show exceptions? - } - - public static void append(StringBuilder str, Method method) - { - append(str, null, method); - } - - public static void append(StringBuilder str, MethodType methodType) - { - str.append(methodType.returnType().getName()); - str.append("("); - boolean delim = false; - for (Class paramType : methodType.parameterList()) - { - if (delim) - str.append(", "); - str.append(paramType.getName()); - delim = true; - } - str.append(")"); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/TextUtil.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/TextUtil.java deleted file mode 100644 index 93ec5b8f5ab..00000000000 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/TextUtil.java +++ /dev/null @@ -1,97 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.common.util; - -/** - * Collection of utility methods for Text content - */ -public final class TextUtil -{ - /** - * Create a hint of what the text is like. - *

- * Used by logging and error messages to get a hint of what the text is like. - * - * @param text the text to abbreviate, quote, and generally give you a hint of what the value is. - * @return the abbreviated text - */ - public static String quote(String text) - { - if (text == null) - { - return ""; - } - return '"' + text + '"'; - } - - /** - * Create a hint of what the text is like. - *

- * Used by logging and error messages to get a hint of what the text is like. - * - * @param text the text to abbreviate, quote, and generally give you a hint of what the value is. - * @return the abbreviated text - */ - public static String hint(String text) - { - if (text == null) - { - return ""; - } - return '"' + maxStringLength(30, text) + '"'; - } - - /** - * Smash a long string to fit within the max string length, by taking the middle section of the string and replacing them with an ellipsis "..." - * - *

-     * Examples:
-     * .maxStringLength( 9, "Eatagramovabits") == "Eat...its"
-     * .maxStringLength(10, "Eatagramovabits") == "Eat...bits"
-     * .maxStringLength(11, "Eatagramovabits") == "Eata...bits"
-     * 
- * - * @param max the maximum size of the string (minimum size supported is 9) - * @param raw the raw string to smash - * @return the ellipsis'd version of the string. - */ - public static String maxStringLength(int max, String raw) - { - int length = raw.length(); - if (length <= max) - { - // already short enough - return raw; - } - - if (max < 9) - { - // minimum supported - return raw.substring(0, max); - } - - StringBuilder ret = new StringBuilder(); - int startLen = (int)Math.round((double)max / (double)3); - ret.append(raw.substring(0, startLen)); - ret.append("..."); - ret.append(raw.substring(length - (max - startLen - 3))); - - return ret.toString(); - } -} diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/DummyFrameHandlerFactory.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/DummyFrameHandlerFactory.java index 5a9b5d5f72b..d7468d6a2d0 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/DummyFrameHandlerFactory.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/DummyFrameHandlerFactory.java @@ -23,7 +23,7 @@ import javax.websocket.ClientEndpointConfig; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; public class DummyFrameHandlerFactory extends JavaxWebSocketFrameHandlerFactory { diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerBadSignaturesTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerBadSignaturesTest.java index d3b63c5e112..cf4b7dc9e75 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerBadSignaturesTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerBadSignaturesTest.java @@ -25,7 +25,7 @@ import javax.websocket.OnError; import javax.websocket.OnOpen; import javax.websocket.Session; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageBinaryTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageBinaryTest.java index f8279a529b4..2d05a5b3e8e 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageBinaryTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageBinaryTest.java @@ -30,7 +30,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.javax.common.sockets.TrackingSocket; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageTextTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageTextTest.java index f786b77d947..ccb95e2674e 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageTextTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandlerOnMessageTextTest.java @@ -30,7 +30,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.javax.common.sockets.TrackingSocket; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSinkTest.java index b633e8b81af..afa3f919c73 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryMessageSinkTest.java @@ -30,10 +30,10 @@ import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EndpointConfig; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.javax.common.AbstractSessionTest; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -50,9 +50,9 @@ public class DecodedBinaryMessageSinkTest extends AbstractMessageSinkTest DecodedCalendarCopy copy = new DecodedCalendarCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Calendar.class); Decoder.Binary decoder = new GmtDecoder(); - DecodedBinaryMessageSink sink = new DecodedBinaryMessageSink(AbstractSessionTest.session, decoder, copyHandle); + DecodedBinaryMessageSink sink = new DecodedBinaryMessageSink(AbstractSessionTest.session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); ByteBuffer data = ByteBuffer.allocate(16); data.putShort((short)1999); data.put((byte)12); @@ -73,11 +73,11 @@ public class DecodedBinaryMessageSinkTest extends AbstractMessageSinkTest DecodedCalendarCopy copy = new DecodedCalendarCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Calendar.class); Decoder.Binary decoder = new GmtDecoder(); - DecodedBinaryMessageSink sink = new DecodedBinaryMessageSink(AbstractSessionTest.session, decoder, copyHandle); + DecodedBinaryMessageSink sink = new DecodedBinaryMessageSink(AbstractSessionTest.session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); ByteBuffer data1 = ByteBuffer.allocate(16); data1.putShort((short)2000); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryStreamMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryStreamMessageSinkTest.java index 75622414870..1fbd4cf03d3 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryStreamMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedBinaryStreamMessageSinkTest.java @@ -33,9 +33,9 @@ import javax.websocket.Decoder; import javax.websocket.EndpointConfig; import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -52,9 +52,9 @@ public class DecodedBinaryStreamMessageSinkTest extends AbstractMessageSinkTest DecodedCalendarCopy copy = new DecodedCalendarCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Calendar.class); Decoder.BinaryStream decoder = new GmtDecoder(); - DecodedBinaryStreamMessageSink sink = new DecodedBinaryStreamMessageSink(session, decoder, copyHandle); + DecodedBinaryStreamMessageSink sink = new DecodedBinaryStreamMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); ByteBuffer data = ByteBuffer.allocate(16); data.putShort((short)1999); data.put((byte)12); @@ -75,11 +75,11 @@ public class DecodedBinaryStreamMessageSinkTest extends AbstractMessageSinkTest DecodedCalendarCopy copy = new DecodedCalendarCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Calendar.class); Decoder.BinaryStream decoder = new GmtDecoder(); - DecodedBinaryStreamMessageSink sink = new DecodedBinaryStreamMessageSink(session, decoder, copyHandle); + DecodedBinaryStreamMessageSink sink = new DecodedBinaryStreamMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); ByteBuffer data1 = ByteBuffer.allocate(16); data1.putShort((short)2000); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSinkTest.java index f1c123f1ade..f805aec78b5 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextMessageSinkTest.java @@ -30,9 +30,9 @@ import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EndpointConfig; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -49,9 +49,9 @@ public class DecodedTextMessageSinkTest extends AbstractMessageSinkTest DecodedDateCopy copy = new DecodedDateCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Date.class); Decoder.Text decoder = new GmtDecoder(); - DecodedTextMessageSink sink = new DecodedTextMessageSink(session, decoder, copyHandle); + DecodedTextMessageSink sink = new DecodedTextMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("2018.02.13").setFin(true), finCallback); finCallback.get(1, TimeUnit.SECONDS); // wait for callback @@ -67,11 +67,11 @@ public class DecodedTextMessageSinkTest extends AbstractMessageSinkTest DecodedDateCopy copy = new DecodedDateCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Date.class); Decoder.Text decoder = new GmtDecoder(); - DecodedTextMessageSink sink = new DecodedTextMessageSink(session, decoder, copyHandle); + DecodedTextMessageSink sink = new DecodedTextMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("2023").setFin(false), callback1); sink.accept(new Frame(OpCode.CONTINUATION).setPayload(".08").setFin(false), callback2); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextStreamMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextStreamMessageSinkTest.java index 6a111e3c794..d33952b6f94 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextStreamMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/DecodedTextStreamMessageSinkTest.java @@ -32,10 +32,10 @@ import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EndpointConfig; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -52,9 +52,9 @@ public class DecodedTextStreamMessageSinkTest extends AbstractMessageSinkTest DecodedDateCopy copy = new DecodedDateCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Date.class); Decoder.TextStream decoder = new GmtDecoder(); - DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session, decoder, copyHandle); + DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("2018.02.13").setFin(true), finCallback); finCallback.get(1, TimeUnit.SECONDS); // wait for callback @@ -70,11 +70,11 @@ public class DecodedTextStreamMessageSinkTest extends AbstractMessageSinkTest DecodedDateCopy copy = new DecodedDateCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Date.class); Decoder.TextStream decoder = new GmtDecoder(); - DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session, decoder, copyHandle); + DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session.getCoreSession(), decoder, copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("2023").setFin(false), callback1); sink.accept(new Frame(OpCode.CONTINUATION).setPayload(".08").setFin(false), callback2); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSinkTest.java index 0064602ecff..eb8a9fb32fe 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSinkTest.java @@ -31,11 +31,12 @@ import java.util.function.Consumer; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.javax.common.AbstractSessionTest; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; +import org.eclipse.jetty.websocket.util.messages.InputStreamMessageSink; import org.junit.jupiter.api.Test; import static java.nio.charset.StandardCharsets.UTF_8; @@ -49,9 +50,9 @@ public class InputStreamMessageSinkTest extends AbstractMessageSinkTest { InputStreamCopy copy = new InputStreamCopy(); MethodHandle copyHandle = getAcceptHandle(copy, InputStream.class); - InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session, copyHandle); + InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session.getCoreSession(), copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); ByteBuffer data = BufferUtil.toBuffer("Hello World", UTF_8); sink.accept(new Frame(OpCode.BINARY).setPayload(data), finCallback); @@ -66,9 +67,9 @@ public class InputStreamMessageSinkTest extends AbstractMessageSinkTest { InputStreamCopy copy = new InputStreamCopy(); MethodHandle copyHandle = getAcceptHandle(copy, InputStream.class); - InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session, copyHandle); + InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session.getCoreSession(), copyHandle); - CompletableFutureCallback fin1Callback = new CompletableFutureCallback(); + FutureCallback fin1Callback = new FutureCallback(); ByteBuffer data1 = BufferUtil.toBuffer("Hello World", UTF_8); sink.accept(new Frame(OpCode.BINARY).setPayload(data1).setFin(true), fin1Callback); @@ -77,7 +78,7 @@ public class InputStreamMessageSinkTest extends AbstractMessageSinkTest assertThat("FinCallback.done", fin1Callback.isDone(), is(true)); assertThat("Writer.contents", new String(byteStream.toByteArray(), UTF_8), is("Hello World")); - CompletableFutureCallback fin2Callback = new CompletableFutureCallback(); + FutureCallback fin2Callback = new FutureCallback(); ByteBuffer data2 = BufferUtil.toBuffer("Greetings Earthling", UTF_8); sink.accept(new Frame(OpCode.BINARY).setPayload(data2).setFin(true), fin2Callback); @@ -92,11 +93,11 @@ public class InputStreamMessageSinkTest extends AbstractMessageSinkTest { InputStreamCopy copy = new InputStreamCopy(); MethodHandle copyHandle = getAcceptHandle(copy, InputStream.class); - InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session, copyHandle); + InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session.getCoreSession(), copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.BINARY).setPayload("Hello").setFin(false), callback1); sink.accept(new Frame(OpCode.CONTINUATION).setPayload(", ").setFin(false), callback2); @@ -116,12 +117,12 @@ public class InputStreamMessageSinkTest extends AbstractMessageSinkTest { InputStreamCopy copy = new InputStreamCopy(); MethodHandle copyHandle = getAcceptHandle(copy, InputStream.class); - InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session, copyHandle); + InputStreamMessageSink sink = new InputStreamMessageSink(AbstractSessionTest.session.getCoreSession(), copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback callback3 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback callback3 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.BINARY).setPayload("Greetings").setFin(false), callback1); sink.accept(new Frame(OpCode.CONTINUATION).setPayload(", ").setFin(false), callback2); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriterTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriterTest.java index b20190b12c2..dfb4a69c006 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriterTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriterTest.java @@ -24,11 +24,14 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import org.eclipse.jetty.io.ByteBufferPool; +import org.eclipse.jetty.io.MappedByteBufferPool; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; +import org.eclipse.jetty.websocket.util.messages.MessageWriter; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -36,11 +39,14 @@ import static org.hamcrest.Matchers.is; public class MessageWriterTest { + private ByteBufferPool bufferPool = new MappedByteBufferPool(); + @Test public void testSingleByteArray512b() throws IOException, InterruptedException { FrameCapture capture = new FrameCapture(); - try (MessageWriter writer = new MessageWriter(capture, 1024)) + capture.setOutputBufferSize(1024); + try (MessageWriter writer = new MessageWriter(capture, bufferPool)) { char[] cbuf = new char[512]; Arrays.fill(cbuf, 'x'); @@ -57,7 +63,8 @@ public class MessageWriterTest public void testSingleByteArray2k() throws IOException, InterruptedException { FrameCapture capture = new FrameCapture(); - try (MessageWriter writer = new MessageWriter(capture, 1024)) + capture.setOutputBufferSize(1024); + try (MessageWriter writer = new MessageWriter(capture, bufferPool)) { char[] cbuf = new char[1024 * 2]; Arrays.fill(cbuf, 'x'); @@ -83,7 +90,8 @@ public class MessageWriterTest final int writerBufferSize = 100; FrameCapture capture = new FrameCapture(); - try (MessageWriter writer = new MessageWriter(capture, writerBufferSize)) + capture.setOutputBufferSize(writerBufferSize); + try (MessageWriter writer = new MessageWriter(capture, bufferPool)) { char[] cbuf = new char[testSize]; Arrays.fill(cbuf, 'x'); @@ -125,7 +133,8 @@ public class MessageWriterTest final int testSize = writerBufferSize + 16; WholeMessageCapture capture = new WholeMessageCapture(); - try (MessageWriter writer = new MessageWriter(capture, writerBufferSize)) + capture.setOutputBufferSize(writerBufferSize); + try (MessageWriter writer = new MessageWriter(capture, bufferPool)) { char[] cbuf = new char[testSize]; Arrays.fill(cbuf, 'x'); @@ -163,7 +172,7 @@ public class MessageWriterTest if (frame.getOpCode() == OpCode.TEXT) activeMessage = new Utf8StringBuilder(); - activeMessage.append(frame.getPayload()); + activeMessage.append(frame.getPayload().slice()); if (frame.isFin()) { diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSinkTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSinkTest.java index 6002b9adb26..3bab792edca 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSinkTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSinkTest.java @@ -28,10 +28,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; +import org.eclipse.jetty.websocket.util.messages.ReaderMessageSink; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -45,9 +46,9 @@ public class ReaderMessageSinkTest extends AbstractMessageSinkTest CompletableFuture copyFuture = new CompletableFuture<>(); ReaderCopy copy = new ReaderCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Reader.class); - ReaderMessageSink sink = new ReaderMessageSink(session, copyHandle); + ReaderMessageSink sink = new ReaderMessageSink(session.getCoreSession(), copyHandle); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("Hello World"), finCallback); finCallback.get(1, TimeUnit.SECONDS); // wait for callback @@ -62,11 +63,11 @@ public class ReaderMessageSinkTest extends AbstractMessageSinkTest CompletableFuture copyFuture = new CompletableFuture<>(); ReaderCopy copy = new ReaderCopy(copyFuture); MethodHandle copyHandle = getAcceptHandle(copy, Reader.class); - ReaderMessageSink sink = new ReaderMessageSink(session, copyHandle); + ReaderMessageSink sink = new ReaderMessageSink(session.getCoreSession(), copyHandle); - CompletableFutureCallback callback1 = new CompletableFutureCallback(); - CompletableFutureCallback callback2 = new CompletableFutureCallback(); - CompletableFutureCallback finCallback = new CompletableFutureCallback(); + FutureCallback callback1 = new FutureCallback(); + FutureCallback callback2 = new FutureCallback(); + FutureCallback finCallback = new FutureCallback(); sink.accept(new Frame(OpCode.TEXT).setPayload("Hello").setFin(false), callback1); sink.accept(new Frame(OpCode.CONTINUATION).setPayload(", ").setFin(false), callback2); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsStaticParamsTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsStaticParamsTest.java index b557a208e39..d9b5b131afe 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsStaticParamsTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsStaticParamsTest.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.websocket.javax.common.util; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; @@ -26,7 +27,8 @@ import javax.websocket.Session; import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketFrameHandlerFactory; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils.Arg; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -57,6 +59,8 @@ public class InvokerUtilsStaticParamsTest return String.format("onColorMessage(%s, '%s', '%s')", color); } } + + private static MethodHandles.Lookup lookup = MethodHandles.lookup(); @Test public void testOnlyParamString() throws Throwable @@ -71,7 +75,7 @@ public class InvokerUtilsStaticParamsTest // Raw Calling Args - none specified // Get basic method handle (without a instance to call against) - this is what the metadata stores - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(Foo.class, method, new NameParamIdentifier(), namedVariables); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, Foo.class, method, new NameParamIdentifier(), namedVariables); // Some point later an actual instance is needed, which has static named parameters Map templateValues = new HashMap<>(); @@ -100,7 +104,7 @@ public class InvokerUtilsStaticParamsTest }; // Get basic method handle (without a instance to call against) - this is what the metadata stores - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(Foo.class, method, new NameParamIdentifier(), namedVariables); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, Foo.class, method, new NameParamIdentifier(), namedVariables); // Some point later an actual instance is needed, which has static named parameters Map templateValues = new HashMap<>(); @@ -128,10 +132,10 @@ public class InvokerUtilsStaticParamsTest "count" }; - final Arg ARG_LABEL = new Arg(String.class).required(); + final InvokerUtils.Arg ARG_LABEL = new InvokerUtils.Arg(String.class).required(); // Get basic method handle (without a instance to call against) - this is what the metadata stores - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(Foo.class, method, new NameParamIdentifier(), namedVariables, ARG_LABEL); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, Foo.class, method, new NameParamIdentifier(), namedVariables, ARG_LABEL); // Some point later an actual instance is needed, which has static named parameters Map templateValues = new HashMap<>(); diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsTest.java index e2b43579d17..54c6e51fa7f 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtilsTest.java @@ -20,9 +20,12 @@ package org.eclipse.jetty.websocket.javax.common.util; import java.io.File; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import org.eclipse.jetty.util.annotation.Name; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -149,11 +152,13 @@ public class InvokerUtilsTest throw new AssertionError("Unable to find method: " + name); } + private static MethodHandles.Lookup lookup = MethodHandles.lookup(); + @Test public void testSimpleInvoker() throws Throwable { Method method = ReflectUtils.findMethod(Simple.class, "onMessage", String.class); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(Simple.class, method, new InvokerUtils.Arg(String.class)); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, Simple.class, method, new InvokerUtils.Arg(String.class)); Simple simple = new Simple(); String result = (String)methodHandle.invoke(simple, "Hello World"); @@ -170,7 +175,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle2 = InvokerUtils.mutatedInvoker(KeyValue.class, method2, callingArgs); + MethodHandle methodHandle2 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method2, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle2.invoke(obj, "Year", 1972); @@ -187,7 +192,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Age", 45); @@ -205,7 +210,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(Boolean.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Age", 45, Boolean.TRUE); @@ -223,7 +228,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Year", 888888L, 2017); @@ -241,7 +246,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, new Simple(), "Count", 1776); @@ -261,7 +266,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(Long.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, new Simple(), "Amount", Boolean.TRUE, 200, 9999L); @@ -279,7 +284,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class, "cost") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); NamedParams obj = new NamedParams(); String result = (String)methodHandle.invoke(obj, "Apple", "Red", 10); @@ -297,7 +302,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class, "color") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); NamedParams obj = new NamedParams(); String result = (String)methodHandle.invoke(obj, 20, "Banana", "Yellow"); @@ -312,7 +317,7 @@ public class InvokerUtilsTest InvokerUtils.Arg[] callingArgs = new InvokerUtils.Arg[]{}; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples); assertThat("Result", result, is("sigEmpty<>")); } @@ -327,7 +332,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus")); assertThat("Result", result, is("sigEmpty<>")); } @@ -342,7 +347,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, null); assertThat("Result", result, is("sigEmpty<>")); } @@ -357,7 +362,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Hello"); assertThat("Result", result, is("sigStr")); } @@ -373,7 +378,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus"), "Hiya"); assertThat("Result", result, is("sigStr")); } @@ -389,7 +394,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Greetings", new File("bogus")); assertThat("Result", result, is("sigStr")); } @@ -405,7 +410,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Name", new File("bogus1")); assertThat("Result", result, is("sigStrFile")); } @@ -421,7 +426,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus2"), "Alt"); assertThat("Result", result, is("sigStrFile")); } @@ -437,7 +442,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Bob", new File("bogus3")); assertThat("Result", result, is("sigFileStr")); } @@ -453,7 +458,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus4"), "Dobalina"); assertThat("Result", result, is("sigFileStr")); } @@ -470,7 +475,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(boolean.class, "fin") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, new File("foo"), "bar", true); assertThat("Result", result, is("sigFileStrFin")); } @@ -487,7 +492,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(boolean.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("baz"), "flem", false); assertThat("Result", result, is("sigFileStrFin")); } @@ -504,7 +509,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, false, new File("foo"), "bar"); assertThat("Result", result, is("sigFileStrFin")); } @@ -521,7 +526,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, true, new File("foo"), "bar"); assertThat("Result", result, is("sigFileStrFin")); } @@ -538,7 +543,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, true, null, "bar"); assertThat("Result", result, is("sigFileStrFin<,bar,true>")); } diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/NameParamIdentifier.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/NameParamIdentifier.java index 655f7e5bc5e..9ecb0e20cf1 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/NameParamIdentifier.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/NameParamIdentifier.java @@ -22,6 +22,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.eclipse.jetty.util.annotation.Name; +import org.eclipse.jetty.websocket.util.InvokerUtils; /** * Simple {@link InvokerUtils.ParamIdentifier} diff --git a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java index 8becc56f33e..9d7026334d9 100644 --- a/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java +++ b/jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java @@ -18,6 +18,7 @@ package org.eclipse.jetty.websocket.javax.common.util; +import org.eclipse.jetty.websocket.util.ReflectUtils; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/jetty-websocket/websocket-javax-server/src/main/config/modules/websocket-javax.mod b/jetty-websocket/websocket-javax-server/src/main/config/modules/websocket-javax.mod index 26f3514a753..62ba7f8f59b 100644 --- a/jetty-websocket/websocket-javax-server/src/main/config/modules/websocket-javax.mod +++ b/jetty-websocket/websocket-javax-server/src/main/config/modules/websocket-javax.mod @@ -12,6 +12,7 @@ annotations [lib] lib/websocket/websocket-core-${jetty.version}.jar +lib/websocket/websocket-util-${jetty.version}.jar lib/websocket/websocket-servlet-${jetty.version}.jar lib/websocket/jetty-javax-websocket-api-1.1.2.jar lib/websocket/websocket-javax-*.jar diff --git a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/DelegatedJavaxServletUpgradeRequest.java b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxServerUpgradeRequest.java similarity index 89% rename from jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/DelegatedJavaxServletUpgradeRequest.java rename to jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxServerUpgradeRequest.java index f03a7fb62d1..9b4d4d55939 100644 --- a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/DelegatedJavaxServletUpgradeRequest.java +++ b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxServerUpgradeRequest.java @@ -24,11 +24,11 @@ import java.security.Principal; import org.eclipse.jetty.websocket.javax.common.UpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; -public class DelegatedJavaxServletUpgradeRequest implements UpgradeRequest +public class JavaxServerUpgradeRequest implements UpgradeRequest { private final ServletUpgradeRequest servletRequest; - public DelegatedJavaxServletUpgradeRequest(ServletUpgradeRequest servletRequest) + public JavaxServerUpgradeRequest(ServletUpgradeRequest servletRequest) { this.servletRequest = servletRequest; } diff --git a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxWebSocketServerFrameHandlerFactory.java b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxWebSocketServerFrameHandlerFactory.java index 50892c5b1af..e070107ac44 100644 --- a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxWebSocketServerFrameHandlerFactory.java +++ b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/JavaxWebSocketServerFrameHandlerFactory.java @@ -61,6 +61,6 @@ public class JavaxWebSocketServerFrameHandlerFactory extends JavaxWebSocketClien @Override public FrameHandler newFrameHandler(Object websocketPojo, ServletUpgradeRequest upgradeRequest, ServletUpgradeResponse upgradeResponse) { - return newJavaxWebSocketFrameHandler(websocketPojo, new DelegatedJavaxServletUpgradeRequest(upgradeRequest)); + return newJavaxWebSocketFrameHandler(websocketPojo, new JavaxServerUpgradeRequest(upgradeRequest)); } } diff --git a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/PathParamIdentifier.java b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/PathParamIdentifier.java index 1d3dae9b83c..3b26056b2cc 100644 --- a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/PathParamIdentifier.java +++ b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/PathParamIdentifier.java @@ -22,7 +22,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.websocket.server.PathParam; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; /** * Method argument identifier for {@link javax.websocket.server.PathParam} annotations. diff --git a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/UpgradeResponseAdapter.java b/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/UpgradeResponseAdapter.java deleted file mode 100644 index 7c9ea9e615b..00000000000 --- a/jetty-websocket/websocket-javax-server/src/main/java/org/eclipse/jetty/websocket/javax/server/internal/UpgradeResponseAdapter.java +++ /dev/null @@ -1,47 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.javax.server.internal; - -import java.util.List; - -import org.eclipse.jetty.websocket.core.ExtensionConfig; -import org.eclipse.jetty.websocket.javax.common.UpgradeResponse; -import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; - -public class UpgradeResponseAdapter implements UpgradeResponse -{ - private final ServletUpgradeResponse servletResponse; - - public UpgradeResponseAdapter(ServletUpgradeResponse servletResponse) - { - this.servletResponse = servletResponse; - } - - @Override - public String getAcceptedSubProtocol() - { - return this.servletResponse.getAcceptedSubProtocol(); - } - - @Override - public List getExtensions() - { - return this.servletResponse.getExtensions(); - } -} diff --git a/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/CompletableFutureMethodHandle.java b/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/CompletableFutureMethodHandle.java index e9a044f4900..3924b2a6552 100644 --- a/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/CompletableFutureMethodHandle.java +++ b/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/CompletableFutureMethodHandle.java @@ -19,18 +19,19 @@ package org.eclipse.jetty.websocket.javax.tests; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.util.concurrent.CompletableFuture; -import org.eclipse.jetty.websocket.javax.common.util.InvokerUtils; -import org.eclipse.jetty.websocket.javax.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; public class CompletableFutureMethodHandle { public static MethodHandle of(Class type, CompletableFuture future) { Method method = ReflectUtils.findMethod(CompletableFuture.class, "complete", type); - MethodHandle completeHandle = InvokerUtils.mutatedInvoker(CompletableFuture.class, method, new InvokerUtils.Arg(type)); + MethodHandle completeHandle = InvokerUtils.mutatedInvoker(MethodHandles.lookup(), CompletableFuture.class, method, new InvokerUtils.Arg(type)); return completeHandle.bindTo(future); } } diff --git a/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/matchers/IsMessageHandlerType.java b/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/matchers/IsMessageHandlerType.java index 5389f4d2e02..325d5fd71a1 100644 --- a/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/matchers/IsMessageHandlerType.java +++ b/jetty-websocket/websocket-javax-tests/src/main/java/org/eclipse/jetty/websocket/javax/tests/matchers/IsMessageHandlerType.java @@ -24,8 +24,8 @@ import javax.websocket.PongMessage; import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; import org.eclipse.jetty.websocket.javax.common.decoders.AvailableDecoders; -import org.eclipse.jetty.websocket.javax.common.util.ReflectUtils; import org.eclipse.jetty.websocket.javax.tests.MessageType; +import org.eclipse.jetty.websocket.util.ReflectUtils; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/client/MessageReceivingTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/client/MessageReceivingTest.java index 09b45a8c47e..c901acc48d2 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/client/MessageReceivingTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/client/MessageReceivingTest.java @@ -47,9 +47,9 @@ import org.eclipse.jetty.websocket.core.FrameHandler; import org.eclipse.jetty.websocket.core.MessageHandler; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.core.server.Negotiation; -import org.eclipse.jetty.websocket.javax.common.util.TextUtil; import org.eclipse.jetty.websocket.javax.tests.CoreServer; import org.eclipse.jetty.websocket.javax.tests.DataUtils; +import org.eclipse.jetty.websocket.util.TextUtil; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableDecodersTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableDecodersTest.java index 2fcdd64de37..a5a93916345 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableDecodersTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableDecodersTest.java @@ -29,9 +29,9 @@ import javax.websocket.EndpointConfig; import org.eclipse.jetty.toolchain.test.Hex; import org.eclipse.jetty.websocket.javax.client.BasicClientEndpointConfig; -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; import org.eclipse.jetty.websocket.javax.common.decoders.AvailableDecoders; import org.eclipse.jetty.websocket.javax.common.decoders.IntegerDecoder; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableEncodersTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableEncodersTest.java index a6ad825ce33..e49e2f7912f 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableEncodersTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/AvailableEncodersTest.java @@ -31,9 +31,9 @@ import javax.websocket.EndpointConfig; import org.eclipse.jetty.toolchain.test.Hex; import org.eclipse.jetty.websocket.javax.client.BasicClientEndpointConfig; -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; import org.eclipse.jetty.websocket.javax.common.encoders.AvailableEncoders; import org.eclipse.jetty.websocket.javax.common.encoders.IntegerEncoder; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/DecoderTextStreamTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/DecoderTextStreamTest.java index 1c0072ff576..43aaa9db5b5 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/DecoderTextStreamTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/coders/DecoderTextStreamTest.java @@ -30,8 +30,8 @@ import java.util.function.Function; import javax.websocket.Decoder; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; +import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.CompletableFutureCallback; import org.eclipse.jetty.websocket.javax.common.messages.DecodedTextStreamMessageSink; import org.eclipse.jetty.websocket.javax.tests.FunctionMethod; import org.eclipse.jetty.websocket.javax.tests.client.AbstractClientSessionTest; @@ -80,14 +80,14 @@ public class DecoderTextStreamTest extends AbstractClientSessionTest return null; }); - DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session, decoder, quoteHandle); + DecodedTextStreamMessageSink sink = new DecodedTextStreamMessageSink(session.getCoreSession(), decoder, quoteHandle); - List callbacks = new ArrayList<>(); - CompletableFutureCallback finCallback = null; + List callbacks = new ArrayList<>(); + FutureCallback finCallback = null; List frames = QuotesUtil.loadAsWebSocketFrames("quotes-ben.txt"); for (Frame frame : frames) { - CompletableFutureCallback callback = new CompletableFutureCallback(); + FutureCallback callback = new FutureCallback(); if (frame.isFin()) { finCallback = callback; @@ -100,7 +100,7 @@ public class DecoderTextStreamTest extends AbstractClientSessionTest finCallback.get(1, TimeUnit.SECONDS); // wait for fin Quotes quotes = futureQuotes.get(1, TimeUnit.SECONDS); assertThat("Quotes", quotes, notNullValue()); - for (CompletableFutureCallback callback : callbacks) + for (FutureCallback callback : callbacks) { assertThat("Callback", callback.isDone(), is(true)); } diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/DeploymentExceptionTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/DeploymentExceptionTest.java index c63c378add7..e8abab0ecc6 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/DeploymentExceptionTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/DeploymentExceptionTest.java @@ -29,7 +29,6 @@ import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; import org.eclipse.jetty.websocket.javax.server.config.JavaxWebSocketServletContainerInitializer; import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidCloseIntSocket; import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidErrorErrorSocket; @@ -37,6 +36,7 @@ import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidErrorIntSoc import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidOpenCloseReasonSocket; import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidOpenIntSocket; import org.eclipse.jetty.websocket.javax.tests.server.sockets.InvalidOpenSessionIntSocket; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; diff --git a/jetty-websocket/websocket-jetty-common/pom.xml b/jetty-websocket/websocket-jetty-common/pom.xml index e8f9990f5f1..5fb6fb314c3 100644 --- a/jetty-websocket/websocket-jetty-common/pom.xml +++ b/jetty-websocket/websocket-jetty-common/pom.xml @@ -56,6 +56,11 @@ websocket-core ${project.version} + + org.eclipse.jetty.websocket + websocket-util + ${project.version} + org.eclipse.jetty jetty-util diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/module-info.java b/jetty-websocket/websocket-jetty-common/src/main/java/module-info.java index 7b455b549fb..b8ecb8308b0 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/module-info.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/module-info.java @@ -22,11 +22,9 @@ import org.eclipse.jetty.websocket.common.ExtensionConfigParser; module org.eclipse.jetty.websocket.jetty.common { exports org.eclipse.jetty.websocket.common; - exports org.eclipse.jetty.websocket.common.invoke; - exports org.eclipse.jetty.websocket.common.message; - exports org.eclipse.jetty.websocket.common.util; requires transitive org.eclipse.jetty.websocket.core; + requires transitive org.eclipse.jetty.websocket.util; requires transitive org.eclipse.jetty.websocket.jetty.api; provides ExtensionConfig.Parser with ExtensionConfigParser; diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/AbstractMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/AbstractMessageSink.java deleted file mode 100644 index 7ccc298eec4..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/AbstractMessageSink.java +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common; - -import java.lang.invoke.MethodHandle; -import java.util.concurrent.Executor; - -public abstract class AbstractMessageSink implements MessageSink -{ - protected final Executor executor; - protected final MethodHandle methodHandle; - - public AbstractMessageSink(Executor executor, MethodHandle methodHandle) - { - this.executor = executor; - this.methodHandle = methodHandle; - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/CompletableFutureCallback.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/CompletableFutureCallback.java deleted file mode 100644 index a5e6c0ddede..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/CompletableFutureCallback.java +++ /dev/null @@ -1,48 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common; - -import java.util.concurrent.CompletableFuture; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - -public class CompletableFutureCallback extends CompletableFuture implements Callback -{ - private static final Logger LOG = Log.getLogger(CompletableFutureCallback.class); - - @Override - public void failed(Throwable cause) - { - if (LOG.isDebugEnabled()) - LOG.debug("failed()", cause); - - completeExceptionally(cause); - } - - @Override - public void succeeded() - { - if (LOG.isDebugEnabled()) - LOG.debug("succeeded()"); - - complete(this); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/FunctionCallException.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/FunctionCallException.java deleted file mode 100644 index b7e56edb528..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/FunctionCallException.java +++ /dev/null @@ -1,51 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.jetty.websocket.core.exception.WebSocketException; - -public class FunctionCallException extends WebSocketException -{ - public FunctionCallException(String message) - { - super(message); - } - - public FunctionCallException(String message, Throwable cause) - { - super(message, cause); - } - - public FunctionCallException(Throwable cause) - { - super(cause); - } - - public Throwable getInvokedCause() - { - Throwable cause = getCause(); - if (cause instanceof InvocationTargetException) - { - return cause.getCause(); - } - return cause; - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java index f62600f4ffb..9f8548f176e 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java @@ -32,7 +32,6 @@ import org.eclipse.jetty.websocket.api.BatchMode; import org.eclipse.jetty.websocket.api.UpgradeRequest; import org.eclipse.jetty.websocket.api.UpgradeResponse; import org.eclipse.jetty.websocket.api.WriteCallback; -import org.eclipse.jetty.websocket.common.invoke.InvalidSignatureException; import org.eclipse.jetty.websocket.core.CloseStatus; import org.eclipse.jetty.websocket.core.Configuration; import org.eclipse.jetty.websocket.core.CoreSession; @@ -46,6 +45,9 @@ import org.eclipse.jetty.websocket.core.exception.ProtocolException; import org.eclipse.jetty.websocket.core.exception.UpgradeException; import org.eclipse.jetty.websocket.core.exception.WebSocketException; import org.eclipse.jetty.websocket.core.exception.WebSocketTimeoutException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.messages.MessageSink; public class JettyWebSocketFrameHandler implements FrameHandler { @@ -152,14 +154,14 @@ public class JettyWebSocketFrameHandler implements FrameHandler customizer.customize(coreSession); session = new WebSocketSession(coreSession, this); - frameHandle = JettyWebSocketFrameHandlerFactory.bindTo(frameHandle, session); - openHandle = JettyWebSocketFrameHandlerFactory.bindTo(openHandle, session); - closeHandle = JettyWebSocketFrameHandlerFactory.bindTo(closeHandle, session); - errorHandle = JettyWebSocketFrameHandlerFactory.bindTo(errorHandle, session); - textHandle = JettyWebSocketFrameHandlerFactory.bindTo(textHandle, session); - binaryHandle = JettyWebSocketFrameHandlerFactory.bindTo(binaryHandle, session); - pingHandle = JettyWebSocketFrameHandlerFactory.bindTo(pingHandle, session); - pongHandle = JettyWebSocketFrameHandlerFactory.bindTo(pongHandle, session); + frameHandle = InvokerUtils.bindTo(frameHandle, session); + openHandle = InvokerUtils.bindTo(openHandle, session); + closeHandle = InvokerUtils.bindTo(closeHandle, session); + errorHandle = InvokerUtils.bindTo(errorHandle, session); + textHandle = InvokerUtils.bindTo(textHandle, session); + binaryHandle = InvokerUtils.bindTo(binaryHandle, session); + pingHandle = InvokerUtils.bindTo(pingHandle, session); + pongHandle = InvokerUtils.bindTo(pongHandle, session); Executor executor = container.getExecutor(); diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerFactory.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerFactory.java index 0168d34612b..f30ea756870 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerFactory.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerFactory.java @@ -24,7 +24,7 @@ import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; -import java.lang.reflect.Constructor; +import java.lang.invoke.MethodType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -37,7 +37,6 @@ import java.util.concurrent.Executor; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.websocket.api.BatchMode; import org.eclipse.jetty.websocket.api.Frame; -import org.eclipse.jetty.websocket.api.InvalidWebSocketException; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketConnectionListener; import org.eclipse.jetty.websocket.api.WebSocketFrameListener; @@ -50,16 +49,19 @@ 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.WebSocket; -import org.eclipse.jetty.websocket.common.invoke.InvalidSignatureException; -import org.eclipse.jetty.websocket.common.invoke.InvokerUtils; -import org.eclipse.jetty.websocket.common.message.ByteArrayMessageSink; -import org.eclipse.jetty.websocket.common.message.ByteBufferMessageSink; -import org.eclipse.jetty.websocket.common.message.InputStreamMessageSink; -import org.eclipse.jetty.websocket.common.message.PartialBinaryMessageSink; -import org.eclipse.jetty.websocket.common.message.PartialTextMessageSink; -import org.eclipse.jetty.websocket.common.message.ReaderMessageSink; -import org.eclipse.jetty.websocket.common.message.StringMessageSink; -import org.eclipse.jetty.websocket.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.core.CoreSession; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidWebSocketException; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.messages.ByteArrayMessageSink; +import org.eclipse.jetty.websocket.util.messages.ByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.InputStreamMessageSink; +import org.eclipse.jetty.websocket.util.messages.MessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.PartialStringMessageSink; +import org.eclipse.jetty.websocket.util.messages.ReaderMessageSink; +import org.eclipse.jetty.websocket.util.messages.StringMessageSink; /** * Factory to create {@link JettyWebSocketFrameHandler} instances suitable for @@ -120,16 +122,16 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle { JettyWebSocketFrameHandlerMetadata metadata = getMetadata(endpointInstance.getClass()); - final MethodHandle openHandle = bindTo(metadata.getOpenHandle(), endpointInstance); - final MethodHandle closeHandle = bindTo(metadata.getCloseHandle(), endpointInstance); - final MethodHandle errorHandle = bindTo(metadata.getErrorHandle(), endpointInstance); - final MethodHandle textHandle = bindTo(metadata.getTextHandle(), endpointInstance); - final MethodHandle binaryHandle = bindTo(metadata.getBinaryHandle(), endpointInstance); + final MethodHandle openHandle = InvokerUtils.bindTo(metadata.getOpenHandle(), endpointInstance); + final MethodHandle closeHandle = InvokerUtils.bindTo(metadata.getCloseHandle(), endpointInstance); + final MethodHandle errorHandle = InvokerUtils.bindTo(metadata.getErrorHandle(), endpointInstance); + final MethodHandle textHandle = InvokerUtils.bindTo(metadata.getTextHandle(), endpointInstance); + final MethodHandle binaryHandle = InvokerUtils.bindTo(metadata.getBinaryHandle(), endpointInstance); final Class textSinkClass = metadata.getTextSink(); final Class binarySinkClass = metadata.getBinarySink(); - final MethodHandle frameHandle = bindTo(metadata.getFrameHandle(), endpointInstance); - final MethodHandle pingHandle = bindTo(metadata.getPingHandle(), endpointInstance); - final MethodHandle pongHandle = bindTo(metadata.getPongHandle(), endpointInstance); + final MethodHandle frameHandle = InvokerUtils.bindTo(metadata.getFrameHandle(), endpointInstance); + final MethodHandle pingHandle = InvokerUtils.bindTo(metadata.getPingHandle(), endpointInstance); + final MethodHandle pongHandle = InvokerUtils.bindTo(metadata.getPongHandle(), endpointInstance); BatchMode batchMode = metadata.getBatchMode(); JettyWebSocketFrameHandler frameHandler = new JettyWebSocketFrameHandler( @@ -154,46 +156,26 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle try { - try - { - Constructor sinkConstructor = sinkClass.getConstructor(Executor.class, MethodHandle.class, Session.class); - MessageSink messageSink = (MessageSink)sinkConstructor.newInstance(executor, msgHandle, session); - return messageSink; - } - catch (NoSuchMethodException e) - { - try - { - Constructor sinkConstructor = sinkClass.getConstructor(Executor.class, MethodHandle.class); - MessageSink messageSink = (MessageSink)sinkConstructor.newInstance(executor, msgHandle); - return messageSink; - } - catch (NoSuchMethodException e2) - { - e.addSuppressed(e2); - throw new RuntimeException("Missing expected MessageSink constructor found at: " + sinkClass.getName(), e); - } - } + MethodHandle ctorHandle = MethodHandles.lookup().findConstructor(sinkClass, + MethodType.methodType(void.class, CoreSession.class, MethodHandle.class)); + return (MessageSink)ctorHandle.invoke(session.getCoreSession(), msgHandle); + } + catch (NoSuchMethodException e) + { + throw new RuntimeException("Missing expected MessageSink constructor found at: " + sinkClass.getName(), e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException("Unable to create MessageSink: " + sinkClass.getName(), e); } - } - - public static MethodHandle bindTo(MethodHandle methodHandle, Object... objs) - { - if (methodHandle == null) - return null; - MethodHandle ret = methodHandle; - for (Object obj : objs) + catch (RuntimeException e) { - if (ret.type().parameterType(0).isAssignableFrom(obj.getClass())) - { - ret = ret.bindTo(obj); - } + throw e; + } + catch (Throwable t) + { + throw new RuntimeException(t); } - return ret; } private MethodHandle toMethodHandle(MethodHandles.Lookup lookup, Method method) @@ -211,8 +193,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle private JettyWebSocketFrameHandlerMetadata createListenerMetadata(Class endpointClass) { JettyWebSocketFrameHandlerMetadata metadata = new JettyWebSocketFrameHandlerMetadata(); - - MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodHandles.Lookup lookup = getMethodHandleLookup(endpointClass); Method openMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketConnect", Session.class); MethodHandle open = toMethodHandle(lookup, openMethod); @@ -255,11 +236,11 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle { Method textMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPartialText", String.class, boolean.class); MethodHandle text = toMethodHandle(lookup, textMethod); - metadata.setTextHandler(PartialTextMessageSink.class, text, textMethod); + metadata.setTextHandler(PartialStringMessageSink.class, text, textMethod); Method binaryMethod = ReflectUtils.findMethod(endpointClass, "onWebSocketPartialBinary", ByteBuffer.class, boolean.class); MethodHandle binary = toMethodHandle(lookup, binaryMethod); - metadata.setBinaryHandle(PartialBinaryMessageSink.class, binary, binaryMethod); + metadata.setBinaryHandle(PartialByteBufferMessageSink.class, binary, binaryMethod); } // Frame Listener @@ -291,6 +272,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle metadata.setIdleTimeout(Duration.ofMillis(max)); metadata.setBatchMode(anno.batchMode()); + MethodHandles.Lookup lookup = getMethodHandleLookup(endpointClass); Method onmethod; // OnWebSocketConnect [0..1] @@ -299,7 +281,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle { assertSignatureValid(endpointClass, onmethod, OnWebSocketConnect.class); final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class).required(); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(endpointClass, onmethod, SESSION); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, endpointClass, onmethod, SESSION); metadata.setOpenHandler(methodHandle, onmethod); } @@ -311,7 +293,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg STATUS_CODE = new InvokerUtils.Arg(int.class); final InvokerUtils.Arg REASON = new InvokerUtils.Arg(String.class); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(endpointClass, onmethod, SESSION, STATUS_CODE, REASON); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, endpointClass, onmethod, SESSION, STATUS_CODE, REASON); // TODO: need mutation of args? ... // Session + CloseInfo -> // setOnClose((closeInfo) ->{ @@ -328,7 +310,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle assertSignatureValid(endpointClass, onmethod, OnWebSocketError.class); final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg CAUSE = new InvokerUtils.Arg(Throwable.class).required(); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(endpointClass, onmethod, SESSION, CAUSE); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, endpointClass, onmethod, SESSION, CAUSE); metadata.setErrorHandler(methodHandle, onmethod); } @@ -339,7 +321,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle assertSignatureValid(endpointClass, onmethod, OnWebSocketFrame.class); final InvokerUtils.Arg SESSION = new InvokerUtils.Arg(Session.class); final InvokerUtils.Arg FRAME = new InvokerUtils.Arg(Frame.class).required(); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(endpointClass, onmethod, SESSION, FRAME); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, endpointClass, onmethod, SESSION, FRAME); metadata.setFrameHandler(methodHandle, onmethod); } @@ -381,7 +363,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle { assertSignatureValid(endpointClass, onMsg, OnWebSocketMessage.class); - MethodHandle methodHandle = InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, InvokerUtils.PARAM_IDENTITY, textCallingArgs); + MethodHandle methodHandle = InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, textCallingArgs); if (methodHandle != null) { // Normal Text Message @@ -390,7 +372,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle continue onmessageloop; } - methodHandle = InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, InvokerUtils.PARAM_IDENTITY, binaryBufferCallingArgs); + methodHandle = InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, binaryBufferCallingArgs); if (methodHandle != null) { // ByteBuffer Binary Message @@ -399,7 +381,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle continue onmessageloop; } - methodHandle = InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, InvokerUtils.PARAM_IDENTITY, binaryArrayCallingArgs); + methodHandle = InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, binaryArrayCallingArgs); if (methodHandle != null) { // byte[] Binary Message @@ -408,7 +390,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle continue onmessageloop; } - methodHandle = InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, InvokerUtils.PARAM_IDENTITY, inputStreamCallingArgs); + methodHandle = InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, inputStreamCallingArgs); if (methodHandle != null) { // InputStream Binary Message @@ -417,7 +399,7 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle continue onmessageloop; } - methodHandle = InvokerUtils.optionalMutatedInvoker(endpointClass, onMsg, InvokerUtils.PARAM_IDENTITY, readerCallingArgs); + methodHandle = InvokerUtils.optionalMutatedInvoker(lookup, endpointClass, onMsg, readerCallingArgs); if (methodHandle != null) { // Reader Text Message @@ -473,6 +455,20 @@ public class JettyWebSocketFrameHandlerFactory extends ContainerLifeCycle throw new InvalidSignatureException(err.toString()); } + private MethodHandles.Lookup getMethodHandleLookup(Class endpointClass) throws InvalidWebSocketException + { + MethodHandles.Lookup lookup; + try + { + lookup = MethodHandles.privateLookupIn(endpointClass, MethodHandles.lookup()); + } + catch (IllegalAccessException e) + { + throw new InvalidWebSocketException("Unable to obtain MethodHandle lookup for " + endpointClass, e); + } + return lookup; + } + @Override public void dump(Appendable out, String indent) throws IOException { diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerMetadata.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerMetadata.java index 345d4a7352f..2e9b6c2ef0f 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerMetadata.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandlerMetadata.java @@ -23,6 +23,7 @@ import java.lang.invoke.MethodHandle; import org.eclipse.jetty.websocket.api.BatchMode; import org.eclipse.jetty.websocket.api.InvalidWebSocketException; import org.eclipse.jetty.websocket.core.Configuration; +import org.eclipse.jetty.websocket.util.messages.MessageSink; public class JettyWebSocketFrameHandlerMetadata extends Configuration.ConfigurationCustomizer { diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvalidSignatureException.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvalidSignatureException.java deleted file mode 100644 index cb4fa91a48b..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvalidSignatureException.java +++ /dev/null @@ -1,72 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.invoke; - -import java.lang.annotation.Annotation; -import java.lang.invoke.MethodType; -import java.lang.reflect.Method; - -import org.eclipse.jetty.websocket.api.InvalidWebSocketException; -import org.eclipse.jetty.websocket.common.util.ReflectUtils; - -@SuppressWarnings("serial") -public class InvalidSignatureException extends InvalidWebSocketException -{ - public static InvalidSignatureException build(Class pojo, Class methodAnnotationClass, Method method) - { - StringBuilder err = new StringBuilder(); - err.append("Invalid "); - if (methodAnnotationClass != null) - { - err.append("@"); - err.append(methodAnnotationClass.getSimpleName()); - err.append(' '); - } - if (pojo != null) - { - ReflectUtils.append(err, method); - } - else - { - ReflectUtils.append(err, pojo, method); - } - return new InvalidSignatureException(err.toString()); - } - - public static InvalidSignatureException build(MethodType expectedType, MethodType actualType) - { - StringBuilder err = new StringBuilder(); - err.append("Invalid MethodHandle "); - ReflectUtils.append(err, actualType); - err.append(" - expected "); - ReflectUtils.append(err, expectedType); - - return new InvalidSignatureException(err.toString()); - } - - public InvalidSignatureException(String message) - { - super(message); - } - - public InvalidSignatureException(String message, Throwable cause) - { - super(message, cause); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtils.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtils.java deleted file mode 100644 index 77c195e9767..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtils.java +++ /dev/null @@ -1,369 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.invoke; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.jetty.websocket.common.util.ReflectUtils; - -public class InvokerUtils -{ - public static class Arg - { - private final Class type; - private boolean required = false; - private String name; - - public Arg(Class type) - { - this.type = type; - } - - public Arg(Class type, String name) - { - this.type = type; - this.name = name; - } - - public String getName() - { - return name; - } - - public boolean matches(Arg other) - { - // If tags exist - if (this.name != null) - { - // They have to match - return (this.name.equals(other.name)); - } - - // Lastly, if types match, use em - return (this.type.isAssignableFrom(other.type)); - } - - public Arg required() - { - this.required = true; - return this; - } - - public Class getType() - { - return type; - } - - public boolean isRequired() - { - return required; - } - } - - public interface ParamIdentifier - { - Arg getParamArg(Method method, Class paramType, int idx); - } - - private static class ParamIdentity implements ParamIdentifier - { - @Override - public Arg getParamArg(Method method, Class paramType, int idx) - { - return new Arg(paramType); - } - } - - public static final ParamIdentifier PARAM_IDENTITY = new ParamIdentity(); - - /** - * Build a MethodHandle that can call the method with the calling args provided. - *

- * Might need to drop calling args and/or reorder the calling args to fit - * the actual method being called. - *

- * - * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) - * @param method the method to invoke - * @param callingArgs the calling arguments - * @return the MethodHandle for this set of CallingArgs - */ - public static MethodHandle mutatedInvoker(Class targetClass, Method method, Arg... callingArgs) - { - return mutatedInvoker(targetClass, method, PARAM_IDENTITY, callingArgs); - } - - /** - * Create a MethodHandle that performs the following layers - *
    - *
  1. {@link MethodHandles#permuteArguments(MethodHandle, MethodType, int...)} - moving calling Args around - * to fit actual actual method parameter arguments (in proper order), with remaining (unused) calling args afterwords
  2. - *
  3. {@link MethodHandles#dropArguments(MethodHandle, int, Class[])} - to drop the unused calling args
  4. - *
  5. {@link MethodHandle#invoke(Object...)} - to call the specific method
  6. - *
- * - * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) - * @param method the method to invoke - * @param paramIdentifier the mechanism to identify parameters in method - * @param callingArgs the calling arguments - * @return the MethodHandle for this set of CallingArgs - * @throws RuntimeException when unable to fit Calling Args to Parameter Types - */ - public static MethodHandle mutatedInvoker(Class targetClass, Method method, ParamIdentifier paramIdentifier, Arg... callingArgs) - { - return mutatedInvoker(targetClass, true, method, paramIdentifier, callingArgs); - } - - private static MethodHandle mutatedInvoker(Class targetClass, boolean throwOnFailure, Method method, ParamIdentifier paramIdentifier, Arg... callingArgs) - { - Class[] parameterTypes = method.getParameterTypes(); - - // Build up Arg list representing the MethodHandle parameters - // ParamIdentifier is used to find named parameters (like javax.websocket's @PathParam declaration) - boolean hasNamedParamArgs = false; - Arg[] parameterArgs = new Arg[parameterTypes.length + 1]; - parameterArgs[0] = new Arg(targetClass); // first type is always the calling object instance type - for (int i = 0; i < parameterTypes.length; i++) - { - Arg arg = paramIdentifier.getParamArg(method, parameterTypes[i], i); - if (arg.name != null) - { - hasNamedParamArgs = true; - } - parameterArgs[i + 1] = arg; - } - - // Parameter to Calling Argument mapping. - // The size of this array must be the the same as the parameterArgs array (or bigger) - if (callingArgs.length < parameterTypes.length) - { - if (!throwOnFailure) - { - return null; - } - - StringBuilder err = new StringBuilder(); - err.append("Target method "); - ReflectUtils.append(err, targetClass, method); - err.append(" contains too many parameters and cannot be mapped to expected callable args "); - appendTypeList(err, callingArgs); - throw new InvalidSignatureException(err.toString()); - } - - // Establish MethodType for supplied calling args - boolean hasNamedCallingArgs = false; - List> cTypes = new ArrayList<>(); - cTypes.add(targetClass); // targetClass always at index 0 - for (int i = 0; i < callingArgs.length; i++) - { - Arg arg = callingArgs[i]; - if (arg.name != null) - { - hasNamedCallingArgs = true; - } - cTypes.add(arg.getType()); - } - MethodType callingType = MethodType.methodType(method.getReturnType(), cTypes); - - // Create low level MethodHandle - MethodHandles.Lookup lookup = MethodHandles.lookup(); - - try - { - // Low level invoker. - // We intentionally do not use lookup#unreflect() as that will incorrectly preserve - // the calling 'refc' type of where the method is declared, not the targetClass. - // That behavior of #unreflect() results in a MethodType referring to the - // base/abstract/interface where the method is declared, and not the targetClass - MethodType rawType = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); - MethodHandle methodHandle = lookup.findVirtual(targetClass, method.getName(), rawType); - - // If callingType and rawType are the same (and there's no named args), - // then there's no need to reorder / permute / drop args - if (!hasNamedCallingArgs && !hasNamedParamArgs && rawType.equals(callingType)) - { - return methodHandle; - } - - // If we reached this point, then we know that the callingType and rawType don't - // match, so we have to drop and/or permute(reorder) the arguments - - // Mapping will be same size as callingType (to compensate for targetClass at index 0) - int[] reorderMap = new int[callingType.parameterCount()]; - Arrays.fill(reorderMap, -1); - reorderMap[0] = 0; // always references targetClass - - // To track which callingArgs have been used. - // If a callingArg is used, it is used only once. - boolean[] usedCallingArgs = new boolean[callingArgs.length]; - Arrays.fill(usedCallingArgs, false); - - // Iterate through each parameterArg and attempt to find an associated callingArg - for (int pi = 1; pi < parameterArgs.length; pi++) - { - int ref = -1; - - // Find a reference to argument in callArgs - for (int ci = 0; ci < callingArgs.length; ci++) - { - if (!usedCallingArgs[ci] && parameterArgs[pi].matches(callingArgs[ci])) - { - ref = ci + 1; // add 1 to compensate for parameter 0 - usedCallingArgs[ci] = true; - break; - } - } - - // Didn't find an unused callingArg that fits this parameterArg - if (ref < 0) - { - if (!throwOnFailure) - { - return null; - } - - StringBuilder err = new StringBuilder(); - err.append("Invalid mapping of type ["); - err.append(parameterArgs[pi].getType()); - err.append("] in method "); - ReflectUtils.append(err, method); - err.append(" to calling args "); - appendTypeList(err, callingArgs); - - throw new InvalidSignatureException(err.toString()); - } - - reorderMap[pi] = ref; - } - - // Remaining unused callingArgs are to be placed at end of specified reorderMap - for (int ri = parameterArgs.length; ri <= reorderMap.length; ri++) - { - for (int uci = 0; uci < usedCallingArgs.length; uci++) - { - if (usedCallingArgs[uci] == false) - { - if (callingArgs[uci].required) - { - if (!throwOnFailure) - { - return null; - } - - StringBuilder err = new StringBuilder(); - err.append("Missing required argument ["); - err.append(callingArgs[uci].getType().getName()); - err.append("] in method "); - ReflectUtils.append(err, method); - - throw new InvalidSignatureException(err.toString()); - } - - reorderMap[ri] = uci + 1; // compensate for parameter 0 - ri++; - } - } - } - - // Drop excess (not mapped to a method parameter) calling args - int idxDrop = parameterArgs.length; - int dropLength = reorderMap.length - idxDrop; - if (dropLength > 0) - { - List> dropTypes = new ArrayList<>(); - for (int i = 0; i < dropLength; i++) - { - int callingTypeIdx = reorderMap[idxDrop + i]; - dropTypes.add(callingType.parameterType(callingTypeIdx)); - } - methodHandle = MethodHandles.dropArguments(methodHandle, idxDrop, dropTypes); - } - - // Reorder calling args to parameter args - methodHandle = MethodHandles.permuteArguments(methodHandle, callingType, reorderMap); - - // Return method handle - return methodHandle; - } - catch (IllegalAccessException | NoSuchMethodException e) - { - // TODO: throw Invalid Invoker Exception - if (!throwOnFailure) - { - return null; - } - - throw new InvalidSignatureException("Unable to obtain MethodHandle for " + method, e); - } - } - - /** - * Create an optional MethodHandle that performs the following layers. - *
    - *
  1. {@link MethodHandles#permuteArguments(MethodHandle, MethodType, int...)} - moving calling Args around - * to fit actual actual method parameter arguments (in proper order), with remaining (unused) calling args afterwords
  2. - *
  3. {@link MethodHandles#dropArguments(MethodHandle, int, Class[])} - to drop the unused calling args
  4. - *
  5. {@link MethodHandle#invoke(Object...)} - to call the specific method
  6. - *
- * - * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) - * @param method the method to invoke - * @param paramIdentifier the mechanism to identify parameters in method - * @param callingArgs the calling arguments - * @return the MethodHandle for this set of CallingArgs, or null if not possible to create MethodHandle with CallingArgs to provided method - */ - public static MethodHandle optionalMutatedInvoker(Class targetClass, Method method, ParamIdentifier paramIdentifier, Arg... callingArgs) - { - return mutatedInvoker(targetClass, false, method, paramIdentifier, callingArgs); - } - - private static void appendTypeList(StringBuilder str, Arg[] args) - { - str.append("("); - boolean comma = false; - for (Arg arg : args) - { - if (comma) - str.append(", "); - str.append(arg.getType().getName()); - comma = true; - } - str.append(")"); - } - - private static void appendTypeList(StringBuilder str, Class[] types) - { - str.append("("); - boolean comma = false; - for (Class type : types) - { - if (comma) - str.append(", "); - str.append(type.getName()); - comma = true; - } - str.append(")"); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteArrayMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteArrayMessageSink.java deleted file mode 100644 index 9973599f9f5..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteArrayMessageSink.java +++ /dev/null @@ -1,105 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.ByteArrayOutputStream; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodType; -import java.nio.ByteBuffer; -import java.util.Objects; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.common.invoke.InvalidSignatureException; -import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; - -public class ByteArrayMessageSink extends AbstractMessageSink -{ - private static final byte[] EMPTY_BUFFER = new byte[0]; - private static final int BUFFER_SIZE = 65535; - private final Session session; - private ByteArrayOutputStream out; - private int size; - - public ByteArrayMessageSink(Executor executor, MethodHandle methodHandle, Session session) - { - super(executor, methodHandle); - this.session = session; - - Objects.requireNonNull(methodHandle, "MethodHandle"); - // byte[] buf, int offset, int length - MethodType onMessageType = MethodType.methodType(Void.TYPE, byte[].class, int.class, int.class); - if (methodHandle.type() != onMessageType) - { - throw InvalidSignatureException.build(onMessageType, methodHandle.type()); - } - } - - @SuppressWarnings("Duplicates") - @Override - public void accept(Frame frame, Callback callback) - { - try - { - if (frame.hasPayload()) - { - ByteBuffer payload = frame.getPayload(); - size = size + payload.remaining(); - long maxMessageSize = session.getMaxBinaryMessageSize(); - if (maxMessageSize > 0 && size > maxMessageSize) - throw new MessageTooLargeException("Message size [" + size + "] exceeds maximum size [" + maxMessageSize + "]"); - - if (out == null) - out = new ByteArrayOutputStream(BUFFER_SIZE); - - BufferUtil.writeTo(payload, out); - } - - if (frame.isFin()) - { - if (out != null) - { - byte[] buf = out.toByteArray(); - methodHandle.invoke(buf, 0, buf.length); - } - else - methodHandle.invoke(EMPTY_BUFFER, 0, 0); - } - - callback.succeeded(); - } - catch (Throwable t) - { - callback.failed(t); - } - finally - { - if (frame.isFin()) - { - // reset - out = null; - size = 0; - } - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/CallbackBuffer.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/CallbackBuffer.java deleted file mode 100644 index 4e69fe06eb9..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/CallbackBuffer.java +++ /dev/null @@ -1,42 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.nio.ByteBuffer; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; - -public class CallbackBuffer -{ - public ByteBuffer buffer; - public Callback callback; - - public CallbackBuffer(Callback callback, ByteBuffer buffer) - { - this.callback = callback; - this.buffer = buffer; - } - - @Override - public String toString() - { - return String.format("CallbackBuffer[%s,%s]", BufferUtil.toDetailString(buffer), callback.getClass().getSimpleName()); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/DispatchedMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/DispatchedMessageSink.java deleted file mode 100644 index ce5ffeb5a05..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/DispatchedMessageSink.java +++ /dev/null @@ -1,176 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.lang.invoke.MethodHandle; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.common.MessageSink; -import org.eclipse.jetty.websocket.core.Frame; - -/** - * Centralized logic for Dispatched Message Handling. - *

- * A Dispatched MessageSink can consist of 1 or more {@link #accept(Frame, Callback)} calls. - *

- * The first {@link #accept(Frame, Callback)} in a message will trigger a dispatch to the - * function specified in the constructor. - *

- * The completion of the dispatched function call is the sign that the next message is suitable - * for processing from the network. (The connection fillAndParse should remain idle for the - * NEXT message until such time as the dispatched function call has completed) - *

- *

- * There are a few use cases we need to handle. - *

- *

- * 1. Normal Processing - *

- *
- *     Connection Thread | DispatchedMessageSink | Thread 2
- *     TEXT                accept()
- *                          - dispatch -           function.read(stream)
- *     CONT                accept()                stream.read()
- *     CONT                accept()                stream.read()
- *     CONT=fin            accept()                stream.read()
- *                           EOF                   stream.read EOF
- *     IDLE
- *                                                 exit method
- *     RESUME(NEXT MSG)
- * 
- *

- * 2. Early Exit (with no activity) - *

- *
- *     Connection Thread | DispatchedMessageSink | Thread 2
- *     TEXT                accept()
- *                          - dispatch -           function.read(stream)
- *     CONT                accept()                exit method (normal return)
- *     IDLE
- *     TIMEOUT
- * 
- *

- * 3. Early Exit (due to exception) - *

- *
- *     Connection Thread | DispatchedMessageSink | Thread 2
- *     TEXT                accept()
- *                          - dispatch -           function.read(stream)
- *     CONT                accept()                exit method (throwable)
- *     callback.fail()
- *     endpoint.onError()
- *     close(error)
- * 
- *

- * 4. Early Exit (with Custom Threading) - *

- *
- *     Connection Thread | DispatchedMessageSink | Thread 2              | Thread 3
- *     TEXT                accept()
- *                          - dispatch -           function.read(stream)
- *                                                 thread.new(stream)      stream.read()
- *                                                 exit method
- *     CONT                accept()                                        stream.read()
- *     CONT                accept()                                        stream.read()
- *     CONT=fin            accept()                                        stream.read()
- *                           EOF                                           stream.read EOF
- *     RESUME(NEXT MSG)
- * 
- * - * @param the type of object to give to user function - * @param the type of object that user function will return - */ -public abstract class DispatchedMessageSink extends AbstractMessageSink -{ - private CompletableFuture dispatchComplete; - private MessageSink typeSink; - - public DispatchedMessageSink(Executor executor, MethodHandle methodHandle) - { - super(executor, methodHandle); - Objects.requireNonNull(this.executor, "Executor"); - } - - public abstract MessageSink newSink(Frame frame); - - public void accept(Frame frame, final Callback callback) - { - if (typeSink == null) - { - typeSink = newSink(frame); - // Dispatch to end user function (will likely start with blocking for data/accept) - dispatchComplete = new CompletableFuture<>(); - executor.execute(() -> - { - final T dispatchedType = (T)typeSink; - try - { - methodHandle.invoke(dispatchedType); - dispatchComplete.complete(null); - } - catch (Throwable throwable) - { - dispatchComplete.completeExceptionally(throwable); - } - }); - } - - final Callback frameCallback; - - if (frame.isFin()) - { - CompletableFuture finComplete = new CompletableFuture<>(); - frameCallback = new Callback() - { - @Override - public void failed(Throwable cause) - { - finComplete.completeExceptionally(cause); - } - - @Override - public void succeeded() - { - finComplete.complete(null); - } - }; - CompletableFuture.allOf(dispatchComplete, finComplete).whenComplete( - (aVoid, throwable) -> - { - typeSink = null; - dispatchComplete = null; - if (throwable != null) - callback.failed(throwable); - else - callback.succeeded(); - }); - } - else - { - // Non-fin-frame - frameCallback = callback; - } - - typeSink.accept(frame, frameCallback); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/InputStreamMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/InputStreamMessageSink.java deleted file mode 100644 index 105bafbf032..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/InputStreamMessageSink.java +++ /dev/null @@ -1,40 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.InputStream; -import java.lang.invoke.MethodHandle; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.websocket.common.MessageSink; -import org.eclipse.jetty.websocket.core.Frame; - -public class InputStreamMessageSink extends DispatchedMessageSink -{ - public InputStreamMessageSink(Executor executor, MethodHandle methodHandle) - { - super(executor, methodHandle); - } - - @Override - public MessageSink newSink(Frame frame) - { - return new MessageInputStream(); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageInputStream.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageInputStream.java deleted file mode 100644 index 7d653983736..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageInputStream.java +++ /dev/null @@ -1,227 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.nio.ByteBuffer; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.common.MessageSink; -import org.eclipse.jetty.websocket.core.Frame; - -/** - * Support class for reading a WebSocket BINARY message via a InputStream. - *

- * An InputStream that can access a queue of ByteBuffer payloads, along with expected InputStream blocking behavior. - *

- */ -public class MessageInputStream extends InputStream implements MessageSink -{ - private static final Logger LOG = Log.getLogger(MessageInputStream.class); - private static final CallbackBuffer EOF = new CallbackBuffer(Callback.NOOP, ByteBuffer.allocate(0).asReadOnlyBuffer()); - private final Deque buffers = new ArrayDeque<>(2); - private final AtomicBoolean closed = new AtomicBoolean(false); - private CallbackBuffer activeFrame; - - @Override - public void accept(Frame frame, Callback callback) - { - if (LOG.isDebugEnabled()) - LOG.debug("accepting {}", frame); - - // If closed, we should just toss incoming payloads into the bit bucket. - if (closed.get()) - { - callback.failed(new IOException("Already Closed")); - return; - } - - if (!frame.hasPayload() && !frame.isFin()) - { - callback.succeeded(); - return; - } - - synchronized (buffers) - { - boolean notify = false; - if (frame.hasPayload()) - { - buffers.offer(new CallbackBuffer(callback, frame.getPayload())); - notify = true; - } - else - { - // We cannot wake up blocking read for a zero length frame. - callback.succeeded(); - } - - if (frame.isFin()) - { - buffers.offer(EOF); - notify = true; - } - - if (notify) - { - // notify other thread - buffers.notify(); - } - } - } - - @Override - public void close() throws IOException - { - if (LOG.isDebugEnabled()) - LOG.debug("close()"); - - if (closed.compareAndSet(false, true)) - { - synchronized (buffers) - { - buffers.offer(EOF); - buffers.notify(); - } - } - super.close(); - } - - public CallbackBuffer getActiveFrame() throws InterruptedIOException - { - if (activeFrame == null) - { - // sync and poll queue - CallbackBuffer result; - synchronized (buffers) - { - try - { - while ((result = buffers.poll()) == null) - { - // TODO: handle read timeout here? - buffers.wait(); - } - } - catch (InterruptedException e) - { - shutdown(); - throw new InterruptedIOException(); - } - } - activeFrame = result; - } - - return activeFrame; - } - - private void shutdown() - { - if (LOG.isDebugEnabled()) - LOG.debug("shutdown()"); - synchronized (buffers) - { - closed.set(true); - Throwable cause = new IOException("Shutdown"); - for (CallbackBuffer buffer : buffers) - { - buffer.callback.failed(cause); - } - // Removed buffers that may have remained in the queue. - buffers.clear(); - } - } - - @Override - public void mark(int readlimit) - { - // Not supported. - } - - @Override - public boolean markSupported() - { - return false; - } - - @Override - public int read() throws IOException - { - byte[] buf = new byte[1]; - while (true) - { - int len = read(buf, 0, 1); - if (len < 0) // EOF - return -1; - if (len > 0) // did read something - return buf[0]; - // reading nothing (len == 0) tries again - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException - { - if (closed.get()) - { - if (LOG.isDebugEnabled()) - LOG.debug("Stream closed"); - return -1; - } - - CallbackBuffer result = getActiveFrame(); - - if (LOG.isDebugEnabled()) - LOG.debug("result = {}", result); - - if (result == EOF) - { - if (LOG.isDebugEnabled()) - LOG.debug("Read EOF"); - shutdown(); - return -1; - } - - // We have content - int fillLen = Math.min(result.buffer.remaining(), len); - result.buffer.get(b, off, fillLen); - - if (!result.buffer.hasRemaining()) - { - activeFrame = null; - result.callback.succeeded(); - } - - // return number of bytes actually copied into buffer - return fillLen; - } - - @Override - public void reset() throws IOException - { - throw new IOException("reset() not supported"); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageOutputStream.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageOutputStream.java deleted file mode 100644 index e86619f52c4..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageOutputStream.java +++ /dev/null @@ -1,218 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -import org.eclipse.jetty.io.ByteBufferPool; -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.FutureCallback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.core.CoreSession; -import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.core.OpCode; - -/** - * Support for writing a single WebSocket BINARY message via a {@link OutputStream} - */ -public class MessageOutputStream extends OutputStream -{ - private static final Logger LOG = Log.getLogger(MessageOutputStream.class); - - private final CoreSession coreSession; - private final ByteBufferPool bufferPool; - private long frameCount; - private long bytesSent; - private Frame frame; - private ByteBuffer buffer; // Kept in fill mode - private Callback callback; - private boolean closed; - - public MessageOutputStream(CoreSession coreSession, int bufferSize, ByteBufferPool bufferPool) - { - this.coreSession = coreSession; - this.bufferPool = bufferPool; - this.buffer = bufferPool.acquire(bufferSize, true); - BufferUtil.flipToFill(buffer); - this.frame = new Frame(OpCode.BINARY); - } - - @Override - public void write(byte[] bytes, int off, int len) throws IOException - { - try - { - send(bytes, off, len); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - @Override - public void write(int b) throws IOException - { - try - { - send(new byte[]{(byte)b}, 0, 1); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - @Override - public void flush() throws IOException - { - try - { - flush(false); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - private void flush(boolean fin) throws IOException - { - synchronized (this) - { - if (closed) - throw new IOException("Stream is closed"); - - closed = fin; - - BufferUtil.flipToFlush(buffer, 0); - frame.setPayload(buffer); - frame.setFin(fin); - - try - { - FutureCallback b = new FutureCallback(); - coreSession.sendFrame(frame, b, false); - b.block(); - assert buffer.remaining() == 0; - } - finally - { - BufferUtil.clearToFill(buffer); - } - - ++frameCount; - // Any flush after the first will be a CONTINUATION frame. - frame = new Frame(OpCode.CONTINUATION); - } - } - - private void send(byte[] bytes, final int offset, final int length) throws IOException - { - synchronized (this) - { - if (closed) - throw new IOException("Stream is closed"); - - int remaining = length; - int off = offset; - int space = buffer.remaining(); - while (remaining > 0) - { - // There may be no space available, we want - // to handle correctly when space == 0. - int size = Math.min(space, remaining); - buffer.put(bytes, off, size); - off += size; - remaining -= size; - space = buffer.remaining(); - if (space == 0) - { - flush(false); - space = buffer.remaining(); - } - } - bytesSent += length; - } - } - - @Override - public void close() throws IOException - { - try - { - flush(true); - bufferPool.release(buffer); - if (LOG.isDebugEnabled()) - LOG.debug("Stream closed, {} frames ({} bytes) sent", frameCount, bytesSent); - // Notify without holding locks. - notifySuccess(); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - public void setCallback(Callback callback) - { - synchronized (this) - { - this.callback = callback; - } - } - - private void notifySuccess() - { - Callback callback; - synchronized (this) - { - callback = this.callback; - } - if (callback != null) - { - callback.succeeded(); - } - } - - private void notifyFailure(Throwable failure) - { - Callback callback; - synchronized (this) - { - callback = this.callback; - } - if (callback != null) - { - callback.failed(failure); - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageWriter.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageWriter.java deleted file mode 100644 index 4bd29905ca6..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageWriter.java +++ /dev/null @@ -1,222 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.IOException; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.FutureCallback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.core.CoreSession; -import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.core.OpCode; - -import static java.nio.charset.StandardCharsets.UTF_8; - -/** - * Support for writing a single WebSocket TEXT message via a {@link Writer} - *

- * Note: Per WebSocket spec, all WebSocket TEXT messages must be encoded in UTF-8 - */ -public class MessageWriter extends Writer -{ - private static final Logger LOG = Log.getLogger(MessageWriter.class); - - private final CharsetEncoder utf8Encoder = UTF_8.newEncoder() - .onUnmappableCharacter(CodingErrorAction.REPORT) - .onMalformedInput(CodingErrorAction.REPORT); - - private final CoreSession coreSession; - private long frameCount; - private Frame frame; - private CharBuffer buffer; - private Callback callback; - private boolean closed; - - public MessageWriter(CoreSession coreSession, int bufferSize) - { - this.coreSession = coreSession; - this.buffer = CharBuffer.allocate(bufferSize); - this.frame = new Frame(OpCode.TEXT); - } - - @Override - public void write(char[] chars, int off, int len) throws IOException - { - try - { - send(chars, off, len); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - @Override - public void write(int c) throws IOException - { - try - { - send(new char[]{(char)c}, 0, 1); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - @Override - public void flush() throws IOException - { - try - { - flush(false); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - private void flush(boolean fin) throws IOException - { - synchronized (this) - { - if (closed) - throw new IOException("Stream is closed"); - - closed = fin; - - buffer.flip(); - ByteBuffer payload = utf8Encoder.encode(buffer); - buffer.flip(); - - if (LOG.isDebugEnabled()) - LOG.debug("flush({}): {}", fin, BufferUtil.toDetailString(payload)); - frame.setPayload(payload); - frame.setFin(fin); - - FutureCallback b = new FutureCallback(); - coreSession.sendFrame(frame, b, false); - b.block(); - - ++frameCount; - // Any flush after the first will be a CONTINUATION frame. - frame = new Frame(OpCode.CONTINUATION); - } - } - - private void send(char[] chars, int offset, int length) throws IOException - { - synchronized (this) - { - if (closed) - throw new IOException("Stream is closed"); - - CharBuffer source = CharBuffer.wrap(chars, offset, length); - - int remaining = length; - - while (remaining > 0) - { - int read = source.read(buffer); - if (read == -1) - { - return; - } - - remaining -= read; - - if (remaining > 0) - { - // If we could not write everything, it means - // that the buffer was full, so flush it. - flush(false); - } - } - } - } - - @Override - public void close() throws IOException - { - try - { - flush(true); - if (LOG.isDebugEnabled()) - LOG.debug("Stream closed, {} frames sent", frameCount); - // Notify without holding locks. - notifySuccess(); - } - catch (Throwable x) - { - // Notify without holding locks. - notifyFailure(x); - throw x; - } - } - - public void setCallback(Callback callback) - { - synchronized (this) - { - this.callback = callback; - } - } - - private void notifySuccess() - { - Callback callback; - synchronized (this) - { - callback = this.callback; - } - if (callback != null) - { - callback.succeeded(); - } - } - - private void notifyFailure(Throwable failure) - { - Callback callback; - synchronized (this) - { - callback = this.callback; - } - if (callback != null) - { - callback.failed(failure); - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialBinaryMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialBinaryMessageSink.java deleted file mode 100644 index 0adbccfc7ba..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialBinaryMessageSink.java +++ /dev/null @@ -1,48 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.lang.invoke.MethodHandle; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.core.Frame; - -public class PartialBinaryMessageSink extends AbstractMessageSink -{ - public PartialBinaryMessageSink(Executor executor, MethodHandle methodHandle) - { - super(executor, methodHandle); - } - - @Override - public void accept(Frame frame, Callback callback) - { - try - { - methodHandle.invoke(frame.getPayload(), frame.isFin()); - callback.succeeded(); - } - catch (Throwable t) - { - callback.failed(t); - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialTextMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialTextMessageSink.java deleted file mode 100644 index c805f92aa6e..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/PartialTextMessageSink.java +++ /dev/null @@ -1,59 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.lang.invoke.MethodHandle; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.Utf8StringBuilder; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.core.Frame; - -public class PartialTextMessageSink extends AbstractMessageSink -{ - private final Utf8StringBuilder utf8Partial; - - public PartialTextMessageSink(Executor executor, MethodHandle methodHandle) - { - super(executor, methodHandle); - this.utf8Partial = new Utf8StringBuilder(); - } - - @Override - public void accept(Frame frame, Callback callback) - { - utf8Partial.append(frame.getPayload()); - String partialText = utf8Partial.takePartialString(); - try - { - methodHandle.invoke(partialText, frame.isFin()); - callback.succeeded(); - } - catch (Throwable t) - { - callback.failed(t); - } - finally - { - if (frame.isFin()) - utf8Partial.reset(); - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ReaderMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ReaderMessageSink.java deleted file mode 100644 index 400d6c47959..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ReaderMessageSink.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.io.Reader; -import java.lang.invoke.MethodHandle; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.websocket.core.Frame; - -public class ReaderMessageSink extends DispatchedMessageSink -{ - public ReaderMessageSink(Executor executor, MethodHandle methodHandle) - { - super(executor, methodHandle); - } - - @Override - public MessageReader newSink(Frame frame) - { - return new MessageReader(new MessageInputStream()); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/StringMessageSink.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/StringMessageSink.java deleted file mode 100644 index 9b868838c39..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/StringMessageSink.java +++ /dev/null @@ -1,105 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.message; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodType; -import java.nio.ByteBuffer; -import java.util.Objects; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.Utf8StringBuilder; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.common.invoke.InvalidSignatureException; -import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; - -public class StringMessageSink extends AbstractMessageSink -{ - private static final Logger LOG = Log.getLogger(StringMessageSink.class); - private final Session session; - private Utf8StringBuilder utf; - private int size = 0; - - public StringMessageSink(Executor executor, MethodHandle methodHandle, Session session) - { - super(executor, methodHandle); - this.session = session; - - // Validate onMessageMethod - Objects.requireNonNull(methodHandle, "MethodHandle"); - MethodType onMessageType = MethodType.methodType(Void.TYPE, String.class); - if (methodHandle.type() != onMessageType) - { - throw InvalidSignatureException.build(onMessageType, methodHandle.type()); - } - - this.size = 0; - } - - @SuppressWarnings("Duplicates") - @Override - public void accept(Frame frame, Callback callback) - { - try - { - if (frame.hasPayload()) - { - ByteBuffer payload = frame.getPayload(); - size = size + payload.remaining(); - long maxMessageSize = session.getMaxTextMessageSize(); - if (maxMessageSize > 0 && size > maxMessageSize) - throw new MessageTooLargeException("Message size [" + size + "] exceeds maximum size [" + maxMessageSize + "]"); - - if (utf == null) - utf = new Utf8StringBuilder(1024); - - if (LOG.isDebugEnabled()) - LOG.debug("Raw Payload {}", BufferUtil.toDetailString(payload)); - - // allow for fast fail of BAD utf (incomplete utf will trigger on messageComplete) - utf.append(payload); - } - - if (frame.isFin()) - { - // notify event - if (utf != null) - methodHandle.invoke(utf.toString()); - else - methodHandle.invoke(""); - - // reset - size = 0; - utf = null; - } - - callback.succeeded(); - } - catch (Throwable t) - { - callback.failed(t); - } - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/Utf8CharBuffer.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/Utf8CharBuffer.java deleted file mode 100644 index 12830436a98..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/Utf8CharBuffer.java +++ /dev/null @@ -1,117 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.util; - -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.StandardCharsets; - -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Utf8Appendable; - -/** - * A CharBuffer wrapped with the Utf8Appendable logic. - */ -public class Utf8CharBuffer extends Utf8Appendable -{ - /** - * Convenience method to wrap a ByteBuffer with a {@link Utf8CharBuffer} - * - * @param buffer the buffer to wrap - * @return the Utf8ByteBuffer for the provided ByteBuffer - */ - public static Utf8CharBuffer wrap(ByteBuffer buffer) - { - return new Utf8CharBuffer(buffer.asCharBuffer()); - } - - private final CharBuffer buffer; - - private Utf8CharBuffer(CharBuffer buffer) - { - super(buffer); - this.buffer = buffer; - } - - public void append(char[] cbuf, int offset, int size) - { - append(BufferUtil.toDirectBuffer(new String(cbuf, offset, size), StandardCharsets.UTF_8)); - } - - public void append(int c) - { - buffer.append((char)c); - } - - public void clear() - { - buffer.position(0); - buffer.limit(buffer.capacity()); - } - - public ByteBuffer getByteBuffer() - { - // remember settings - int limit = buffer.limit(); - int position = buffer.position(); - - // flip to flush - buffer.limit(buffer.position()); - buffer.position(0); - - // get byte buffer - ByteBuffer bb = StandardCharsets.UTF_8.encode(buffer); - - // restor settings - buffer.limit(limit); - buffer.position(position); - - return bb; - } - - @Override - public int length() - { - return buffer.capacity(); - } - - @Override - public String getPartialString() - { - throw new UnsupportedOperationException("Cannot get Partial String from Utf8CharBuffer"); - } - - public int remaining() - { - return buffer.remaining(); - } - - @Override - public String toString() - { - StringBuilder str = new StringBuilder(); - str.append("Utf8CharBuffer@").append(hashCode()); - str.append("[p=").append(buffer.position()); - str.append(",l=").append(buffer.limit()); - str.append(",c=").append(buffer.capacity()); - str.append(",r=").append(buffer.remaining()); - str.append("]"); - return str.toString(); - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/main/resources/META-INF/services/org.eclipse.jetty.websocket.common.reflect.ArgIdentifier b/jetty-websocket/websocket-jetty-common/src/main/resources/META-INF/services/org.eclipse.jetty.websocket.common.reflect.ArgIdentifier deleted file mode 100644 index 815310b16b6..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/main/resources/META-INF/services/org.eclipse.jetty.websocket.common.reflect.ArgIdentifier +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.jetty.websocket.common.reflect.NameArgIdentifier diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/LocalEndpointMetadataTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/LocalEndpointMetadataTest.java index dc532dc8b73..15f8bc40d9e 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/LocalEndpointMetadataTest.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/LocalEndpointMetadataTest.java @@ -34,10 +34,12 @@ import org.eclipse.jetty.websocket.common.endpoints.annotated.MyStatelessEchoSoc import org.eclipse.jetty.websocket.common.endpoints.annotated.NoopSocket; import org.eclipse.jetty.websocket.common.endpoints.listeners.ListenerBasicSocket; import org.eclipse.jetty.websocket.common.endpoints.listeners.ListenerFrameSocket; -import org.eclipse.jetty.websocket.common.message.ByteArrayMessageSink; -import org.eclipse.jetty.websocket.common.message.InputStreamMessageSink; -import org.eclipse.jetty.websocket.common.message.ReaderMessageSink; -import org.eclipse.jetty.websocket.common.message.StringMessageSink; +import org.eclipse.jetty.websocket.util.DuplicateAnnotationException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.messages.ByteArrayMessageSink; +import org.eclipse.jetty.websocket.util.messages.InputStreamMessageSink; +import org.eclipse.jetty.websocket.util.messages.ReaderMessageSink; +import org.eclipse.jetty.websocket.util.messages.StringMessageSink; import org.hamcrest.Matcher; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -94,7 +96,7 @@ public class LocalEndpointMetadataTest public void testAnnotatedBadDuplicateFrameSocket() throws Exception { // Should toss exception - Exception e = assertThrows(InvalidWebSocketException.class, () -> createMetadata(BadDuplicateFrameSocket.class)); + Exception e = assertThrows(DuplicateAnnotationException.class, () -> createMetadata(BadDuplicateFrameSocket.class)); assertThat(e.getMessage(), containsString("Duplicate @OnWebSocketFrame")); } @@ -105,7 +107,7 @@ public class LocalEndpointMetadataTest public void testAnnotatedBadSignatureNonVoidReturn() throws Exception { // Should toss exception - Exception e = assertThrows(InvalidWebSocketException.class, () -> createMetadata(BadBinarySignatureSocket.class)); + Exception e = assertThrows(InvalidSignatureException.class, () -> createMetadata(BadBinarySignatureSocket.class)); assertThat(e.getMessage(), containsString("must be void")); } @@ -116,7 +118,7 @@ public class LocalEndpointMetadataTest public void testAnnotatedBadSignatureStatic() throws Exception { // Should toss exception - Exception e = assertThrows(InvalidWebSocketException.class, () -> createMetadata(BadTextSignatureSocket.class)); + Exception e = assertThrows(InvalidSignatureException.class, () -> createMetadata(BadTextSignatureSocket.class)); assertThat(e.getMessage(), containsString("must not be static")); } diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageInputStreamTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageInputStreamTest.java index 967d3a60b75..2da4c887af7 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageInputStreamTest.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageInputStreamTest.java @@ -28,9 +28,9 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.IO; -import org.eclipse.jetty.websocket.common.message.MessageInputStream; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; +import org.eclipse.jetty.websocket.util.messages.MessageInputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageOutputStreamTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageOutputStreamTest.java index f22c5932747..8645de9cc6b 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageOutputStreamTest.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageOutputStreamTest.java @@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.common.message.MessageOutputStream; +import org.eclipse.jetty.websocket.util.messages.MessageOutputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -53,12 +53,13 @@ public class MessageOutputStreamTest public void setupTest() throws Exception { sessionCapture = new OutgoingMessageCapture(); + sessionCapture.setOutputBufferSize(OUTPUT_BUFFER_SIZE); } @Test public void testMultipleWrites() throws Exception { - try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, OUTPUT_BUFFER_SIZE, bufferPool)) + try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, bufferPool)) { stream.write("Hello".getBytes("UTF-8")); stream.write(" ".getBytes("UTF-8")); @@ -74,7 +75,7 @@ public class MessageOutputStreamTest @Test public void testSingleWrite() throws Exception { - try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, OUTPUT_BUFFER_SIZE, bufferPool)) + try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, bufferPool)) { stream.write("Hello World".getBytes("UTF-8")); } @@ -94,7 +95,7 @@ public class MessageOutputStreamTest Arrays.fill(buf, (byte)'x'); buf[bufsize - 1] = (byte)'o'; // mark last entry for debugging - try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, OUTPUT_BUFFER_SIZE, bufferPool)) + try (MessageOutputStream stream = new MessageOutputStream(sessionCapture, bufferPool)) { stream.write(buf); } diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageWriterTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageWriterTest.java index 418333d44e4..b77c09669b0 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageWriterTest.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/MessageWriterTest.java @@ -22,7 +22,7 @@ import java.util.Arrays; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.common.message.MessageWriter; +import org.eclipse.jetty.websocket.util.messages.MessageWriter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -49,12 +49,13 @@ public class MessageWriterTest public void setupSession() { remoteSocket = new OutgoingMessageCapture(); + remoteSocket.setOutputBufferSize(OUTPUT_BUFFER_SIZE); } @Test public void testMultipleWrites() throws Exception { - try (MessageWriter stream = new MessageWriter(remoteSocket, OUTPUT_BUFFER_SIZE)) + try (MessageWriter stream = new MessageWriter(remoteSocket, bufferPool)) { stream.write("Hello"); stream.write(" "); @@ -69,7 +70,7 @@ public class MessageWriterTest @Test public void testSingleWrite() throws Exception { - try (MessageWriter stream = new MessageWriter(remoteSocket, OUTPUT_BUFFER_SIZE)) + try (MessageWriter stream = new MessageWriter(remoteSocket, bufferPool)) { stream.append("Hello World"); } @@ -89,7 +90,7 @@ public class MessageWriterTest Arrays.fill(buf, 'x'); buf[size - 1] = 'o'; // mark last entry for debugging - try (MessageWriter stream = new MessageWriter(remoteSocket, OUTPUT_BUFFER_SIZE)) + try (MessageWriter stream = new MessageWriter(remoteSocket, bufferPool)) { stream.write(buf); } diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/OutgoingMessageCapture.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/OutgoingMessageCapture.java index 204fb0b5ec3..691eea4649a 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/OutgoingMessageCapture.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/OutgoingMessageCapture.java @@ -21,9 +21,7 @@ package org.eclipse.jetty.websocket.common; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; -import java.net.SocketAddress; import java.nio.ByteBuffer; -import java.time.Duration; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; @@ -31,18 +29,13 @@ import org.eclipse.jetty.toolchain.test.Hex; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.websocket.api.RemoteEndpoint; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.SuspendToken; -import org.eclipse.jetty.websocket.api.UpgradeRequest; -import org.eclipse.jetty.websocket.api.UpgradeResponse; -import org.eclipse.jetty.websocket.api.WebSocketBehavior; -import org.eclipse.jetty.websocket.common.message.ByteBufferMessageSink; -import org.eclipse.jetty.websocket.common.message.StringMessageSink; import org.eclipse.jetty.websocket.core.CloseStatus; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; +import org.eclipse.jetty.websocket.util.messages.ByteBufferMessageSink; +import org.eclipse.jetty.websocket.util.messages.MessageSink; +import org.eclipse.jetty.websocket.util.messages.StringMessageSink; public class OutgoingMessageCapture extends CoreSession.Empty implements CoreSession { @@ -106,7 +99,7 @@ public class OutgoingMessageCapture extends CoreSession.Empty implements CoreSes String event = String.format("TEXT:fin=%b:len=%d", frame.isFin(), frame.getPayloadLength()); LOG.debug(event); events.offer(event); - messageSink = new StringMessageSink(null, wholeTextHandle, getFakeSession()); + messageSink = new StringMessageSink(this, wholeTextHandle); break; } case OpCode.BINARY: @@ -114,7 +107,7 @@ public class OutgoingMessageCapture extends CoreSession.Empty implements CoreSes String event = String.format("BINARY:fin=%b:len=%d", frame.isFin(), frame.getPayloadLength()); LOG.debug(event); events.offer(event); - messageSink = new ByteBufferMessageSink(null, wholeBinaryHandle, getFakeSession()); + messageSink = new ByteBufferMessageSink(this, wholeBinaryHandle); break; } case OpCode.CONTINUATION: @@ -180,167 +173,4 @@ public class OutgoingMessageCapture extends CoreSession.Empty implements CoreSes hint.append(']'); return hint.toString(); } - - private Session getFakeSession() - { - return new Session() - { - @Override - public void close() - { - } - - @Override - public void close(org.eclipse.jetty.websocket.api.CloseStatus closeStatus) - { - } - - @Override - public void close(int statusCode, String reason) - { - } - - @Override - public void disconnect() - { - } - - @Override - public SocketAddress getLocalAddress() - { - return null; - } - - @Override - public String getProtocolVersion() - { - return null; - } - - @Override - public RemoteEndpoint getRemote() - { - return null; - } - - @Override - public SocketAddress getRemoteAddress() - { - return null; - } - - @Override - public UpgradeRequest getUpgradeRequest() - { - return null; - } - - @Override - public UpgradeResponse getUpgradeResponse() - { - return null; - } - - @Override - public boolean isOpen() - { - return false; - } - - @Override - public boolean isSecure() - { - return false; - } - - @Override - public SuspendToken suspend() - { - return null; - } - - @Override - public WebSocketBehavior getBehavior() - { - return null; - } - - @Override - public Duration getIdleTimeout() - { - return null; - } - - @Override - public int getInputBufferSize() - { - return 0; - } - - @Override - public int getOutputBufferSize() - { - return 0; - } - - @Override - public long getMaxBinaryMessageSize() - { - return maxMessageSize; - } - - @Override - public long getMaxTextMessageSize() - { - return maxMessageSize; - } - - @Override - public long getMaxFrameSize() - { - return 0; - } - - @Override - public boolean isAutoFragment() - { - return false; - } - - @Override - public void setIdleTimeout(Duration duration) - { - } - - @Override - public void setInputBufferSize(int size) - { - } - - @Override - public void setOutputBufferSize(int size) - { - } - - @Override - public void setMaxBinaryMessageSize(long size) - { - } - - @Override - public void setMaxTextMessageSize(long size) - { - } - - @Override - public void setMaxFrameSize(long maxFrameSize) - { - } - - @Override - public void setAutoFragment(boolean autoFragment) - { - } - }; - } } diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryArraySocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryArraySocket.java index a915a11cfa6..1f69bc65dce 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryArraySocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryArraySocket.java @@ -24,7 +24,7 @@ import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; @WebSocket public class AnnotatedBinaryArraySocket diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryStreamSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryStreamSocket.java index 87802cdebe3..31bb675172f 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryStreamSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedBinaryStreamSocket.java @@ -26,7 +26,7 @@ import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextSocket.java index fe53d7cbd7e..ac273aae049 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextSocket.java @@ -25,7 +25,7 @@ import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; @WebSocket public class AnnotatedTextSocket diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextStreamSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextStreamSocket.java index 0c9c8085b50..d5e4b892e72 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextStreamSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/annotated/AnnotatedTextStreamSocket.java @@ -26,7 +26,7 @@ import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; +import org.eclipse.jetty.websocket.util.TextUtil; @WebSocket public class AnnotatedTextStreamSocket diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerBasicSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerBasicSocket.java index f938776a2ba..7afae82387d 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerBasicSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerBasicSocket.java @@ -21,8 +21,8 @@ package org.eclipse.jetty.websocket.common.endpoints.listeners; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; import org.eclipse.jetty.websocket.core.CloseStatus; +import org.eclipse.jetty.websocket.util.TextUtil; public class ListenerBasicSocket implements WebSocketListener { diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerFrameSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerFrameSocket.java index 42410b2ab6f..b4d4ae3b524 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerFrameSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerFrameSocket.java @@ -22,8 +22,8 @@ import org.eclipse.jetty.websocket.api.Frame; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketFrameListener; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; import org.eclipse.jetty.websocket.core.CloseStatus; +import org.eclipse.jetty.websocket.util.TextUtil; public class ListenerFrameSocket implements WebSocketFrameListener { diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPartialSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPartialSocket.java index dd54ccffa34..902681e84b3 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPartialSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPartialSocket.java @@ -24,8 +24,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketPartialListener; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; import org.eclipse.jetty.websocket.core.CloseStatus; +import org.eclipse.jetty.websocket.util.TextUtil; public class ListenerPartialSocket implements WebSocketPartialListener { diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPingPongSocket.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPingPongSocket.java index d910b51bc09..0260092904c 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPingPongSocket.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/endpoints/listeners/ListenerPingPongSocket.java @@ -24,8 +24,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketPingPongListener; import org.eclipse.jetty.websocket.common.EventQueue; -import org.eclipse.jetty.websocket.common.util.TextUtil; import org.eclipse.jetty.websocket.core.CloseStatus; +import org.eclipse.jetty.websocket.util.TextUtil; public class ListenerPingPongSocket implements WebSocketPingPongListener { diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeRequest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeRequest.java deleted file mode 100644 index d99a8d0c0e4..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeRequest.java +++ /dev/null @@ -1,205 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.handshake; - -import java.net.HttpCookie; -import java.net.URI; -import java.security.Principal; -import java.util.List; -import java.util.Map; - -import org.eclipse.jetty.websocket.api.UpgradeRequest; -import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig; - -public class DummyUpgradeRequest implements UpgradeRequest -{ - @Override - public void addExtensions(ExtensionConfig... configs) - { - - } - - @Override - public void addExtensions(String... configs) - { - - } - - @Override - public List getCookies() - { - return null; - } - - @Override - public List getExtensions() - { - return null; - } - - @Override - public String getHeader(String name) - { - return null; - } - - @Override - public int getHeaderInt(String name) - { - return 0; - } - - @Override - public Map> getHeaders() - { - return null; - } - - @Override - public List getHeaders(String name) - { - return null; - } - - @Override - public String getHost() - { - return null; - } - - @Override - public String getHttpVersion() - { - return null; - } - - @Override - public String getMethod() - { - return null; - } - - @Override - public String getOrigin() - { - return null; - } - - @Override - public Map> getParameterMap() - { - return null; - } - - @Override - public String getProtocolVersion() - { - return null; - } - - @Override - public String getQueryString() - { - return null; - } - - @Override - public URI getRequestURI() - { - return null; - } - - @Override - public Object getSession() - { - return null; - } - - @Override - public List getSubProtocols() - { - return null; - } - - @Override - public Principal getUserPrincipal() - { - return null; - } - - @Override - public boolean hasSubProtocol(String test) - { - return false; - } - - @Override - public boolean isSecure() - { - return false; - } - - @Override - public void setCookies(List cookies) - { - - } - - @Override - public void setExtensions(List configs) - { - - } - - @Override - public void setHeader(String name, List values) - { - - } - - @Override - public void setHeader(String name, String value) - { - - } - - @Override - public void setHeaders(Map> headers) - { - - } - - @Override - public void setSession(Object session) - { - - } - - @Override - public void setSubProtocols(List protocols) - { - - } - - @Override - public void setSubProtocols(String... protocols) - { - - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeResponse.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeResponse.java deleted file mode 100644 index 9b55fb6bba2..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/handshake/DummyUpgradeResponse.java +++ /dev/null @@ -1,108 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.handshake; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.jetty.websocket.api.UpgradeResponse; -import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig; - -public class DummyUpgradeResponse implements UpgradeResponse -{ - @Override - public void addHeader(String name, String value) - { - - } - - @Override - public String getAcceptedSubProtocol() - { - return null; - } - - @Override - public List getExtensions() - { - return null; - } - - @Override - public String getHeader(String name) - { - return null; - } - - @Override - public Set getHeaderNames() - { - return null; - } - - @Override - public Map> getHeaders() - { - return null; - } - - @Override - public List getHeaders(String name) - { - return null; - } - - @Override - public int getStatusCode() - { - return 0; - } - - @Override - public void sendForbidden(String message) throws IOException - { - - } - - @Override - public void setAcceptedSubProtocol(String protocol) - { - - } - - @Override - public void setExtensions(List extensions) - { - - } - - @Override - public void setHeader(String name, String value) - { - - } - - @Override - public void setStatusCode(int statusCode) - { - - } -} diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtilsTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtilsTest.java index 80292d0b1ef..315d7ee4fe7 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtilsTest.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/InvokerUtilsTest.java @@ -20,10 +20,12 @@ package org.eclipse.jetty.websocket.common.invoke; import java.io.File; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import org.eclipse.jetty.util.annotation.Name; -import org.eclipse.jetty.websocket.common.util.ReflectUtils; +import org.eclipse.jetty.websocket.util.InvokerUtils; +import org.eclipse.jetty.websocket.util.ReflectUtils; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; @@ -149,11 +151,13 @@ public class InvokerUtilsTest throw new AssertionError("Unable to find method: " + name); } + private static MethodHandles.Lookup lookup = MethodHandles.lookup(); + @Test public void testSimpleInvoker() throws Throwable { Method method = ReflectUtils.findMethod(Simple.class, "onMessage", String.class); - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(Simple.class, method, new InvokerUtils.Arg(String.class)); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, Simple.class, method, new InvokerUtils.Arg(String.class)); Simple simple = new Simple(); String result = (String)methodHandle.invoke(simple, "Hello World"); @@ -170,7 +174,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle2 = InvokerUtils.mutatedInvoker(KeyValue.class, method2, callingArgs); + MethodHandle methodHandle2 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method2, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle2.invoke(obj, "Year", 1972); @@ -187,7 +191,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Age", 45); @@ -205,7 +209,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(Boolean.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Age", 45, Boolean.TRUE); @@ -223,7 +227,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, "Year", 888888L, 2017); @@ -241,7 +245,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, new Simple(), "Count", 1776); @@ -261,7 +265,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(Long.class) }; - MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(KeyValue.class, method1, callingArgs); + MethodHandle methodHandle1 = InvokerUtils.mutatedInvoker(lookup, KeyValue.class, method1, callingArgs); KeyValue obj = new KeyValue(); String result = (String)methodHandle1.invoke(obj, new Simple(), "Amount", Boolean.TRUE, 200, 9999L); @@ -279,7 +283,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(int.class, "cost") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(NamedParams.class, method, new NameParamIdentifier(), callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); NamedParams obj = new NamedParams(); String result = (String)methodHandle.invoke(obj, "Apple", "Red", 10); @@ -297,7 +301,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class, "color") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(NamedParams.class, method, new NameParamIdentifier(), callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, NamedParams.class, method, new NameParamIdentifier(), null, callingArgs); NamedParams obj = new NamedParams(); String result = (String)methodHandle.invoke(obj, 20, "Banana", "Yellow"); @@ -312,7 +316,7 @@ public class InvokerUtilsTest InvokerUtils.Arg[] callingArgs = new InvokerUtils.Arg[]{}; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples); assertThat("Result", result, is("sigEmpty<>")); } @@ -327,7 +331,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus")); assertThat("Result", result, is("sigEmpty<>")); } @@ -342,7 +346,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, null); assertThat("Result", result, is("sigEmpty<>")); } @@ -357,7 +361,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Hello"); assertThat("Result", result, is("sigStr")); } @@ -373,7 +377,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus"), "Hiya"); assertThat("Result", result, is("sigStr")); } @@ -389,7 +393,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Greetings", new File("bogus")); assertThat("Result", result, is("sigStr")); } @@ -405,7 +409,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Name", new File("bogus1")); assertThat("Result", result, is("sigStrFile")); } @@ -421,7 +425,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus2"), "Alt"); assertThat("Result", result, is("sigStrFile")); } @@ -437,7 +441,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(File.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, "Bob", new File("bogus3")); assertThat("Result", result, is("sigFileStr")); } @@ -453,7 +457,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("bogus4"), "Dobalina"); assertThat("Result", result, is("sigFileStr")); } @@ -470,7 +474,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(boolean.class, "fin") }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, new File("foo"), "bar", true); assertThat("Result", result, is("sigFileStrFin")); } @@ -487,7 +491,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(boolean.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, new File("baz"), "flem", false); assertThat("Result", result, is("sigFileStrFin")); } @@ -504,7 +508,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, false, new File("foo"), "bar"); assertThat("Result", result, is("sigFileStrFin")); } @@ -521,7 +525,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, callingArgs); String result = (String)methodHandle.invoke(samples, true, new File("foo"), "bar"); assertThat("Result", result, is("sigFileStrFin")); } @@ -538,7 +542,7 @@ public class InvokerUtilsTest new InvokerUtils.Arg(String.class) }; - MethodHandle methodHandle = InvokerUtils.mutatedInvoker(SampleSignatures.class, method, new NameParamIdentifier(), callingArgs); + MethodHandle methodHandle = InvokerUtils.mutatedInvoker(lookup, SampleSignatures.class, method, new NameParamIdentifier(), null, callingArgs); String result = (String)methodHandle.invoke(samples, true, null, "bar"); assertThat("Result", result, is("sigFileStrFin<,bar,true>")); } diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/NameParamIdentifier.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/NameParamIdentifier.java index 86bd042d7c3..5caedfa43cb 100644 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/NameParamIdentifier.java +++ b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/invoke/NameParamIdentifier.java @@ -22,9 +22,10 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.eclipse.jetty.util.annotation.Name; +import org.eclipse.jetty.websocket.util.InvokerUtils; /** - * Simple {@link org.eclipse.jetty.websocket.common.invoke.InvokerUtils.ParamIdentifier} + * Simple {@link InvokerUtils.ParamIdentifier} * that observes {@link Name} tagged method parameters. */ public class NameParamIdentifier implements InvokerUtils.ParamIdentifier diff --git a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/util/Utf8CharBufferTest.java b/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/util/Utf8CharBufferTest.java deleted file mode 100644 index e9412fab36f..00000000000 --- a/jetty-websocket/websocket-jetty-common/src/test/java/org/eclipse/jetty/websocket/common/util/Utf8CharBufferTest.java +++ /dev/null @@ -1,126 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under -// the terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0 -// -// This Source Code may also be made available under the following -// Secondary Licenses when the conditions for such availability set -// forth in the Eclipse Public License, v. 2.0 are satisfied: -// the Apache License v2.0 which is available at -// https://www.apache.org/licenses/LICENSE-2.0 -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.websocket.common.util; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; - -import org.eclipse.jetty.util.BufferUtil; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -public class Utf8CharBufferTest -{ - private static String asString(ByteBuffer buffer) - { - return BufferUtil.toUTF8String(buffer); - } - - private static byte[] asUTF(String str) - { - return str.getBytes(StandardCharsets.UTF_8); - } - - @Test - public void testAppendGetAppendGet() - { - ByteBuffer buf = ByteBuffer.allocate(128); - Utf8CharBuffer utf = Utf8CharBuffer.wrap(buf); - - byte[] hellobytes = asUTF("Hello "); - byte[] worldbytes = asUTF("World!"); - - utf.append(hellobytes, 0, hellobytes.length); - ByteBuffer hellobuf = utf.getByteBuffer(); - utf.append(worldbytes, 0, worldbytes.length); - ByteBuffer worldbuf = utf.getByteBuffer(); - - assertThat("Hello buffer", asString(hellobuf), is("Hello ")); - assertThat("World buffer", asString(worldbuf), is("Hello World!")); - } - - @Test - public void testAppendGetClearAppendGet() - { - int bufsize = 128; - ByteBuffer buf = ByteBuffer.allocate(bufsize); - Utf8CharBuffer utf = Utf8CharBuffer.wrap(buf); - - int expectedSize = bufsize / 2; - assertThat("Remaining (initial)", utf.remaining(), is(expectedSize)); - - byte[] hellobytes = asUTF("Hello World"); - - utf.append(hellobytes, 0, hellobytes.length); - ByteBuffer hellobuf = utf.getByteBuffer(); - - assertThat("Remaining (after append)", utf.remaining(), is(expectedSize - hellobytes.length)); - assertThat("Hello buffer", asString(hellobuf), is("Hello World")); - - utf.clear(); - - assertThat("Remaining (after clear)", utf.remaining(), is(expectedSize)); - - byte[] whatnowbytes = asUTF("What Now?"); - utf.append(whatnowbytes, 0, whatnowbytes.length); - ByteBuffer whatnowbuf = utf.getByteBuffer(); - - assertThat("Remaining (after 2nd append)", utf.remaining(), is(expectedSize - whatnowbytes.length)); - assertThat("What buffer", asString(whatnowbuf), is("What Now?")); - } - - @Test - public void testAppendUnicodeGetBuffer() - { - ByteBuffer buf = ByteBuffer.allocate(64); - Utf8CharBuffer utf = Utf8CharBuffer.wrap(buf); - - // @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck - byte[] bb = asUTF("Hello A\u00ea\u00f1\u00fcC"); - utf.append(bb, 0, bb.length); - - ByteBuffer actual = utf.getByteBuffer(); - assertThat("Buffer length should be retained", actual.remaining(), is(bb.length)); - assertThat("Message", asString(actual), is("Hello A\u00ea\u00f1\u00fcC")); - } - - @Test - public void testSimpleGetBuffer() - { - int bufsize = 64; - ByteBuffer buf = ByteBuffer.allocate(bufsize); - Utf8CharBuffer utf = Utf8CharBuffer.wrap(buf); - - int expectedSize = bufsize / 2; - assertThat("Remaining (initial)", utf.remaining(), is(expectedSize)); - - byte[] bb = asUTF("Hello World"); - utf.append(bb, 0, bb.length); - - expectedSize -= bb.length; - assertThat("Remaining (after append)", utf.remaining(), is(expectedSize)); - - ByteBuffer actual = utf.getByteBuffer(); - assertThat("Buffer length", actual.remaining(), is(bb.length)); - - assertThat("Message", asString(actual), is("Hello World")); - } -} diff --git a/jetty-websocket/websocket-jetty-server/src/main/config/modules/websocket-jetty.mod b/jetty-websocket/websocket-jetty-server/src/main/config/modules/websocket-jetty.mod index e5fd060373f..6f6469bb54c 100644 --- a/jetty-websocket/websocket-jetty-server/src/main/config/modules/websocket-jetty.mod +++ b/jetty-websocket/websocket-jetty-server/src/main/config/modules/websocket-jetty.mod @@ -12,6 +12,7 @@ annotations [lib] lib/websocket/websocket-core-${jetty.version}.jar +lib/websocket/websocket-util-${jetty.version}.jar lib/websocket/websocket-servlet-${jetty.version}.jar lib/websocket/websocket-jetty-*.jar diff --git a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/ErrorCloseTest.java b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/ErrorCloseTest.java index 646c4ffb100..7f0ee5e8f37 100644 --- a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/ErrorCloseTest.java +++ b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/ErrorCloseTest.java @@ -37,16 +37,17 @@ import org.eclipse.jetty.websocket.api.WebSocketSessionListener; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.common.WebSocketSession; +import org.eclipse.jetty.websocket.core.internal.WebSocketCoreSession; import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -134,16 +135,18 @@ public class ErrorCloseTest } @Test - @Disabled("Merge from 9.4.x broke this") public void testOnOpenThrows() throws Exception { serverSocket.methodsToThrow.add("onOpen"); EventSocket clientSocket = new EventSocket(); - client.connect(clientSocket, serverUri).get(5, TimeUnit.SECONDS); - assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS)); - assertTrue(clientSocket.closeLatch.await(5, TimeUnit.SECONDS)); - assertThat(serverSocket.error.getMessage(), is("throwing from onOpen")); + try (StacklessLogging stacklessLogging = new StacklessLogging(WebSocketCoreSession.class)) + { + client.connect(clientSocket, serverUri).get(5, TimeUnit.SECONDS); + assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientSocket.closeLatch.await(5, TimeUnit.SECONDS)); + assertThat(serverSocket.error.getMessage(), containsString("throwing from onOpen")); + } // Check we have stopped the WebSocketSession properly. assertFalse(serverSocket.session.isOpen()); diff --git a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/client/ClientCloseTest.java b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/client/ClientCloseTest.java index f6396f5a6f3..1d857ee5a2a 100644 --- a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/client/ClientCloseTest.java +++ b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/client/ClientCloseTest.java @@ -212,7 +212,7 @@ public class ClientCloseTest confirmConnection(clientSocket, clientConnectFuture); clientSocket.getSession().getRemote().sendString("too-large-message"); - clientSocket.assertReceivedCloseEvent(timeout, is(StatusCode.MESSAGE_TOO_LARGE), containsString("exceeds maximum size")); + clientSocket.assertReceivedCloseEvent(timeout, is(StatusCode.MESSAGE_TOO_LARGE), containsString("Text message too large")); // client should have noticed the error assertThat("OnError Latch", clientSocket.errorLatch.await(2, SECONDS), is(true)); diff --git a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/server/PartialListenerTest.java b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/server/PartialListenerTest.java index 141f7e3bb65..5733c87d828 100644 --- a/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/server/PartialListenerTest.java +++ b/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/server/PartialListenerTest.java @@ -40,7 +40,6 @@ import org.eclipse.jetty.websocket.api.util.WSURI; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.common.WebSocketSession; -import org.eclipse.jetty.websocket.common.util.TextUtil; import org.eclipse.jetty.websocket.server.JettyServerUpgradeRequest; import org.eclipse.jetty.websocket.server.JettyServerUpgradeResponse; import org.eclipse.jetty.websocket.server.JettyWebSocketCreator; @@ -48,6 +47,7 @@ import org.eclipse.jetty.websocket.server.JettyWebSocketServlet; import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory; import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.eclipse.jetty.websocket.tests.CloseTrackingEndpoint; +import org.eclipse.jetty.websocket.util.TextUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/jetty-websocket/websocket-servlet/src/main/java/org/eclipse/jetty/websocket/servlet/WebSocketMapping.java b/jetty-websocket/websocket-servlet/src/main/java/org/eclipse/jetty/websocket/servlet/WebSocketMapping.java index 93467bc7139..cfe489215cc 100644 --- a/jetty-websocket/websocket-servlet/src/main/java/org/eclipse/jetty/websocket/servlet/WebSocketMapping.java +++ b/jetty-websocket/websocket-servlet/src/main/java/org/eclipse/jetty/websocket/servlet/WebSocketMapping.java @@ -285,11 +285,7 @@ public class WebSocketMapping implements Dumpable, LifeCycle.Listener return null; } - FrameHandler frameHandler = factory.newFrameHandler(websocketPojo, upgradeRequest, upgradeResponse); - if (frameHandler != null) - return frameHandler; - - return null; + return factory.newFrameHandler(websocketPojo, upgradeRequest, upgradeResponse); } @Override diff --git a/jetty-websocket/websocket-util/pom.xml b/jetty-websocket/websocket-util/pom.xml new file mode 100644 index 00000000000..dece207f4d3 --- /dev/null +++ b/jetty-websocket/websocket-util/pom.xml @@ -0,0 +1,60 @@ + + + + org.eclipse.jetty.websocket + websocket-parent + 10.0.0-SNAPSHOT + + + 4.0.0 + websocket-util + Jetty :: Websocket :: org.eclipse.jetty.websocket :: Util + + + ${project.groupId}.util + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + ban-java-servlet-api + + enforce + + + + + + javax.servlet + servletapi + org.eclipse.jetty.orbit:javax.servlet + org.mortbay.jetty:servlet-api + jetty:servlet-api + jetty-servlet-api + + + + + + + + + + + + + org.eclipse.jetty.websocket + websocket-core + ${project.version} + + + org.eclipse.jetty.toolchain + jetty-test-helper + test + + + diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/package-info.java b/jetty-websocket/websocket-util/src/main/java/module-info.java similarity index 78% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/package-info.java rename to jetty-websocket/websocket-util/src/main/java/module-info.java index 2cf20b6630b..06dadf1a9a5 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/package-info.java +++ b/jetty-websocket/websocket-util/src/main/java/module-info.java @@ -16,8 +16,10 @@ // ======================================================================== // -/** - * Jetty WebSocket Common : Message Handling - */ -package org.eclipse.jetty.websocket.common.message; +module org.eclipse.jetty.websocket.util +{ + exports org.eclipse.jetty.websocket.util; + exports org.eclipse.jetty.websocket.util.messages; + requires transitive org.eclipse.jetty.websocket.core; +} diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/DuplicateAnnotationException.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/DuplicateAnnotationException.java similarity index 93% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/DuplicateAnnotationException.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/DuplicateAnnotationException.java index 81cf7af79ff..df3a7b49fa8 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/DuplicateAnnotationException.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/DuplicateAnnotationException.java @@ -16,13 +16,11 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common.util; +package org.eclipse.jetty.websocket.util; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import org.eclipse.jetty.websocket.api.InvalidWebSocketException; - @SuppressWarnings("serial") public class DuplicateAnnotationException extends InvalidWebSocketException { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvalidSignatureException.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidSignatureException.java similarity index 94% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvalidSignatureException.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidSignatureException.java index 7078ddf261a..388b0faae47 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvalidSignatureException.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidSignatureException.java @@ -16,14 +16,12 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.util; +package org.eclipse.jetty.websocket.util; import java.lang.annotation.Annotation; import java.lang.invoke.MethodType; import java.lang.reflect.Method; -import org.eclipse.jetty.websocket.javax.common.InvalidWebSocketException; - @SuppressWarnings("serial") public class InvalidSignatureException extends InvalidWebSocketException { diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/InvalidWebSocketException.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidWebSocketException.java similarity index 96% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/InvalidWebSocketException.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidWebSocketException.java index db69c1b8131..8b8329f4e38 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/InvalidWebSocketException.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvalidWebSocketException.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common; +package org.eclipse.jetty.websocket.util; import org.eclipse.jetty.websocket.core.exception.WebSocketException; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtils.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvokerUtils.java similarity index 89% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtils.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvokerUtils.java index c18f6142fc4..c09827cc608 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/util/InvokerUtils.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/InvokerUtils.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.util; +package org.eclipse.jetty.websocket.util; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -165,14 +165,15 @@ public class InvokerUtils * the actual method being called. *

* + * @param lookup the {@link java.lang.invoke.MethodHandles.Lookup} instance to use. * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) * @param method the method to invoke * @param callingArgs the calling arguments. This is the array of arguments that will always be passed into the returned MethodHandle. * They will be present in the {@link MethodHandle#type()} in the order specified in this array. */ - public static MethodHandle mutatedInvoker(Class targetClass, Method method, Arg... callingArgs) + public static MethodHandle mutatedInvoker(MethodHandles.Lookup lookup, Class targetClass, Method method, Arg... callingArgs) { - return mutatedInvoker(targetClass, method, PARAM_IDENTITY, null, callingArgs); + return mutatedInvoker(lookup, targetClass, true, method, PARAM_IDENTITY, null, callingArgs); } /** @@ -193,6 +194,7 @@ public class InvokerUtils *
  • The next parameters are all of the provided {@code callingArg} types
  • * * + * @param lookup the {@link java.lang.invoke.MethodHandles.Lookup} instance to use. * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) * @param method the method to invoke * @param paramIdentifier the mechanism to identify parameters in method @@ -204,13 +206,13 @@ public class InvokerUtils * @return the MethodHandle for this set of CallingArgs * @throws RuntimeException when unable to fit Calling Args to Parameter Types */ - public static MethodHandle mutatedInvoker(Class targetClass, Method method, ParamIdentifier paramIdentifier, String[] namedVariables, Arg... callingArgs) + public static MethodHandle mutatedInvoker(MethodHandles.Lookup lookup, Class targetClass, Method method, ParamIdentifier paramIdentifier, String[] namedVariables, Arg... callingArgs) { - return mutatedInvoker(targetClass, true, method, paramIdentifier, namedVariables, callingArgs); + return mutatedInvoker(lookup, targetClass, true, method, paramIdentifier, namedVariables, callingArgs); } - @SuppressWarnings("Duplicates") - private static MethodHandle mutatedInvoker(Class targetClass, boolean throwOnFailure, Method method, ParamIdentifier paramIdentifier, + private static MethodHandle mutatedInvoker(MethodHandles.Lookup lookup, Class targetClass, boolean throwOnFailure, + Method method, ParamIdentifier paramIdentifier, String[] namedVariables, Arg... rawCallingArgs) { Class[] parameterTypes = method.getParameterTypes(); @@ -239,17 +241,15 @@ public class InvokerUtils // ParamIdentifier is used to find named parameters (like javax.websocket's @PathParam declaration) boolean hasNamedParamArgs = false; Arg[] parameterArgs = new Arg[parameterTypes.length + 1]; + parameterArgs[0] = new Arg(targetClass); // first type is always the calling object instance type + for (int i = 0; i < parameterTypes.length; i++) { - parameterArgs[0] = new Arg(targetClass); // first type is always the calling object instance type - for (int i = 0; i < parameterTypes.length; i++) + Arg arg = paramIdentifier.getParamArg(method, parameterTypes[i], i); + if (arg.name != null) { - Arg arg = paramIdentifier.getParamArg(method, parameterTypes[i], i); - if (arg.name != null) - { - hasNamedParamArgs = true; - } - parameterArgs[i + 1] = arg; + hasNamedParamArgs = true; } + parameterArgs[i + 1] = arg; } // Parameter to Calling Argument mapping. @@ -292,15 +292,12 @@ public class InvokerUtils try { - MethodType callingType = MethodType.methodType(method.getReturnType(), cTypes); - - // Create low level MethodHandle - MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(targetClass, MethodHandles.lookup()); // Low level invoker. // We intentionally do not use lookup#unreflect() as that will incorrectly preserve // the calling 'refc' type of where the method is declared, not the targetClass. // That behavior of #unreflect() results in a MethodType referring to the // base/abstract/interface where the method is declared, and not the targetClass + MethodType callingType = MethodType.methodType(method.getReturnType(), cTypes); MethodType rawType = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); MethodHandle methodHandle = lookup.findVirtual(targetClass, method.getName(), rawType); @@ -444,6 +441,7 @@ public class InvokerUtils *
  • {@link MethodHandle#invoke(Object...)} - to call the specific method
  • * * + * @param lookup the {@link java.lang.invoke.MethodHandles.Lookup} instance to use. * @param targetClass the target class for invocations of the resulting MethodHandle (also known as parameter 0) * @param method the method to invoke * @param paramIdentifier the mechanism to identify parameters in method @@ -454,10 +452,15 @@ public class InvokerUtils * They will be present in the {@link MethodHandle#type()} in the order specified in this array. * @return the MethodHandle for this set of CallingArgs, or null if not possible to create MethodHandle with CallingArgs to provided method */ - public static MethodHandle optionalMutatedInvoker(Class targetClass, Method method, ParamIdentifier paramIdentifier, String[] namedVariables, - Arg... callingArgs) + public static MethodHandle optionalMutatedInvoker(MethodHandles.Lookup lookup, Class targetClass, Method method, ParamIdentifier paramIdentifier, + String[] namedVariables, Arg... callingArgs) { - return mutatedInvoker(targetClass, false, method, paramIdentifier, namedVariables, callingArgs); + return mutatedInvoker(lookup, targetClass, false, method, paramIdentifier, namedVariables, callingArgs); + } + + public static MethodHandle optionalMutatedInvoker(MethodHandles.Lookup lookup, Class targetClass, Method method, Arg... callingArgs) + { + return mutatedInvoker(lookup, targetClass, false, method, PARAM_IDENTITY, null, callingArgs); } private static void appendTypeList(StringBuilder str, Arg[] args) diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/ReflectUtils.java similarity index 99% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/ReflectUtils.java index c3efa01cc0b..c038b45ead2 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/ReflectUtils.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common.util; +package org.eclipse.jetty.websocket.util; import java.lang.annotation.Annotation; import java.lang.invoke.MethodType; @@ -30,8 +30,6 @@ import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; -import org.eclipse.jetty.websocket.api.InvalidWebSocketException; - public class ReflectUtils { diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/TextUtil.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/TextUtil.java similarity index 98% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/TextUtil.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/TextUtil.java index 76cff1ddc1c..21a2a138d1a 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/util/TextUtil.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/TextUtil.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common.util; +package org.eclipse.jetty.websocket.util; /** * Collection of utility methods for Text content diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/AbstractMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/AbstractMessageSink.java similarity index 71% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/AbstractMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/AbstractMessageSink.java index d3d9e4e6d0d..14d1cc85713 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/AbstractMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/AbstractMessageSink.java @@ -16,22 +16,21 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; import java.util.Objects; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.MessageSink; +import org.eclipse.jetty.websocket.core.CoreSession; public abstract class AbstractMessageSink implements MessageSink { - protected final JavaxWebSocketSession session; + protected final CoreSession session; protected final MethodHandle methodHandle; - public AbstractMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public AbstractMessageSink(CoreSession session, MethodHandle methodHandle) { - this.session = Objects.requireNonNull(session, "JavaxWebSocketSession"); + this.session = Objects.requireNonNull(session, "CoreSession"); this.methodHandle = Objects.requireNonNull(methodHandle, "MethodHandle"); } } diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteArrayMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteArrayMessageSink.java similarity index 80% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteArrayMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteArrayMessageSink.java index 1ee45487212..831b33ffc15 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ByteArrayMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteArrayMessageSink.java @@ -16,20 +16,19 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.ByteArrayOutputStream; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.nio.ByteBuffer; -import java.util.Objects; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; public class ByteArrayMessageSink extends AbstractMessageSink { @@ -38,13 +37,12 @@ public class ByteArrayMessageSink extends AbstractMessageSink private ByteArrayOutputStream out; private int size; - public ByteArrayMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public ByteArrayMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); - Objects.requireNonNull(methodHandle, "MethodHandle"); // byte[] buf - MethodType onMessageType = MethodType.methodType(Void.TYPE, byte[].class); + MethodType onMessageType = MethodType.methodType(Void.TYPE, byte[].class, int.class, int.class); if (methodHandle.type().changeReturnType(void.class) != onMessageType.changeReturnType(void.class)) { throw InvalidSignatureException.build(onMessageType, methodHandle.type()); @@ -60,12 +58,12 @@ public class ByteArrayMessageSink extends AbstractMessageSink if (frame.hasPayload()) { ByteBuffer payload = frame.getPayload(); - size += payload.remaining(); - if (session.getMaxBinaryMessageBufferSize() > 0 && size > session.getMaxBinaryMessageBufferSize()) + long maxBinaryMessageSize = session.getMaxBinaryMessageSize(); + if (maxBinaryMessageSize > 0 && size > maxBinaryMessageSize) { throw new MessageTooLargeException(String.format("Binary message too large: (actual) %,d > (configured max binary buffer size) %,d", - size, session.getMaxBinaryMessageBufferSize())); + size, maxBinaryMessageSize)); } if (out == null) @@ -79,10 +77,10 @@ public class ByteArrayMessageSink extends AbstractMessageSink if (out != null) { byte[] buf = out.toByteArray(); - methodHandle.invoke(buf); + methodHandle.invoke(buf, 0, buf.length); } else - methodHandle.invoke(EMPTY_BUFFER); + methodHandle.invoke(EMPTY_BUFFER, 0, 0); } callback.succeeded(); diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteBufferMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteBufferMessageSink.java similarity index 77% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteBufferMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteBufferMessageSink.java index 131f82137d4..5f86a66e607 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/ByteBufferMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ByteBufferMessageSink.java @@ -16,34 +16,30 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common.message; +package org.eclipse.jetty.websocket.util.messages; import java.io.ByteArrayOutputStream; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.nio.ByteBuffer; import java.util.Objects; -import java.util.concurrent.Executor; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.common.AbstractMessageSink; -import org.eclipse.jetty.websocket.common.invoke.InvalidSignatureException; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; public class ByteBufferMessageSink extends AbstractMessageSink { private static final int BUFFER_SIZE = 65535; - private final Session session; private ByteArrayOutputStream out; private int size; - public ByteBufferMessageSink(Executor executor, MethodHandle methodHandle, Session session) + public ByteBufferMessageSink(CoreSession session, MethodHandle methodHandle) { - super(executor, methodHandle); - this.session = session; + super(session, methodHandle); // Validate onMessageMethod Objects.requireNonNull(methodHandle, "MethodHandle"); @@ -63,10 +59,13 @@ public class ByteBufferMessageSink extends AbstractMessageSink if (frame.hasPayload()) { ByteBuffer payload = frame.getPayload(); - size = size + payload.remaining(); - long maxMessageSize = session.getMaxBinaryMessageSize(); - if (maxMessageSize > 0 && size > maxMessageSize) - throw new MessageTooLargeException("Message size [" + size + "] exceeds maximum size [" + maxMessageSize + "]"); + size += payload.remaining(); + long maxBinaryMessageSize = session.getMaxBinaryMessageSize(); + if (maxBinaryMessageSize > 0 && size > maxBinaryMessageSize) + { + throw new MessageTooLargeException(String.format("Binary message too large: (actual) %,d > (configured max binary message size) %,d", + size, maxBinaryMessageSize)); + } if (out == null) out = new ByteArrayOutputStream(BUFFER_SIZE); diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/CallbackBuffer.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/CallbackBuffer.java similarity index 95% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/CallbackBuffer.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/CallbackBuffer.java index d7ea97c26a1..afe76cfec22 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/CallbackBuffer.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/CallbackBuffer.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.nio.ByteBuffer; import java.util.Objects; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DispatchedMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/DispatchedMessageSink.java similarity index 91% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DispatchedMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/DispatchedMessageSink.java index eb19d230554..f4eab98533d 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/DispatchedMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/DispatchedMessageSink.java @@ -16,17 +16,14 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; -import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.MessageSink; /** * Centralized logic for Dispatched Message Handling. @@ -102,15 +99,12 @@ import org.eclipse.jetty.websocket.javax.common.MessageSink; @SuppressWarnings("Duplicates") public abstract class DispatchedMessageSink extends AbstractMessageSink { - private final Executor executor; private CompletableFuture dispatchComplete; private MessageSink typeSink; - public DispatchedMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public DispatchedMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); - this.executor = session.getContainerImpl().getExecutor(); - Objects.requireNonNull(this.executor, "Executor"); } public abstract MessageSink newSink(Frame frame); @@ -122,7 +116,7 @@ public abstract class DispatchedMessageSink extends AbstractMessageSink typeSink = newSink(frame); // Dispatch to end user function (will likely start with blocking for data/accept) dispatchComplete = new CompletableFuture<>(); - executor.execute(() -> + new Thread(() -> { final T dispatchedType = (T)typeSink; try @@ -134,7 +128,7 @@ public abstract class DispatchedMessageSink extends AbstractMessageSink { dispatchComplete.completeExceptionally(throwable); } - }); + }).start(); } final Callback frameCallback; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/InputStreamMessageSink.java similarity index 79% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/InputStreamMessageSink.java index ffd91c2ddce..b8413b1c1c9 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/InputStreamMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/InputStreamMessageSink.java @@ -16,18 +16,17 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.InputStream; import java.lang.invoke.MethodHandle; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.MessageSink; public class InputStreamMessageSink extends DispatchedMessageSink { - public InputStreamMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public InputStreamMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); } diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageInputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java similarity index 98% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageInputStream.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java index dd489f3f187..6e454bfb4d9 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageInputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.IOException; import java.io.InputStream; @@ -30,7 +30,6 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.MessageSink; /** * Support class for reading a WebSocket BINARY message via a InputStream. diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageOutputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java similarity index 77% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageOutputStream.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java index bbf4a4688f8..92bac19a7b1 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageOutputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.IOException; import java.io.OutputStream; @@ -41,20 +41,26 @@ public class MessageOutputStream extends OutputStream private final CoreSession coreSession; private final ByteBufferPool bufferPool; + private final int bufferSize; private long frameCount; private long bytesSent; - private Frame frame; private ByteBuffer buffer; private Callback callback; private boolean closed; + private byte messageOpCode = OpCode.BINARY; - public MessageOutputStream(CoreSession coreSession, int bufferSize, ByteBufferPool bufferPool) + public MessageOutputStream(CoreSession coreSession, ByteBufferPool bufferPool) { this.coreSession = coreSession; this.bufferPool = bufferPool; + this.bufferSize = coreSession.getOutputBufferSize(); this.buffer = bufferPool.acquire(bufferSize, true); - BufferUtil.flipToFill(buffer); - this.frame = new Frame(OpCode.BINARY); + BufferUtil.clear(buffer); + } + + void setMessageType(byte opcode) + { + this.messageOpCode = opcode; } @Override @@ -62,7 +68,7 @@ public class MessageOutputStream extends OutputStream { try { - send(bytes, off, len); + send(ByteBuffer.wrap(bytes, off, len)); } catch (Throwable x) { @@ -77,7 +83,7 @@ public class MessageOutputStream extends OutputStream { try { - send(new byte[]{(byte)b}, 0, 1); + send(ByteBuffer.wrap(new byte[]{(byte)b})); } catch (Throwable x) { @@ -110,8 +116,7 @@ public class MessageOutputStream extends OutputStream throw new IOException("Stream is closed"); closed = fin; - - BufferUtil.flipToFlush(buffer, 0); + Frame frame = new Frame(frameCount == 0 ? messageOpCode : OpCode.CONTINUATION); frame.setPayload(buffer); frame.setFin(fin); @@ -120,43 +125,40 @@ public class MessageOutputStream extends OutputStream coreSession.sendFrame(frame, b, false); b.block(); - ++frameCount; // Any flush after the first will be a CONTINUATION frame. - frame = new Frame(OpCode.CONTINUATION); + bytesSent += initialBufferSize; + ++frameCount; // Buffer has been sent, but buffer should not have been consumed. - assert buffer.remaining() == initialBufferSize; - - BufferUtil.clearToFill(buffer); + try + { + assert buffer.remaining() == initialBufferSize; + BufferUtil.clear(buffer); + } + catch (Throwable t) + { + t.printStackTrace(); + } } } - private void send(byte[] bytes, final int offset, final int length) throws IOException + private void send(ByteBuffer data) throws IOException { synchronized (this) { if (closed) throw new IOException("Stream is closed"); - int remaining = length; - int off = offset; - while (remaining > 0) + while (data.hasRemaining()) { - // There may be no space available, we want - // to handle correctly when space == 0. - int space = buffer.remaining(); - int size = Math.min(space, remaining); - buffer.put(bytes, off, size); - off += size; - remaining -= size; - if (remaining > 0) - { - // If we could not write everything, it means - // that the buffer was full, so flush it. + int bufferRemainingSpace = bufferSize - buffer.remaining(); + int copied = Math.min(bufferRemainingSpace, data.remaining()); + BufferUtil.append(buffer, data.array(), data.arrayOffset() + data.position(), copied); + data.position(data.position() + copied); + + if (data.hasRemaining()) flush(false); - } } - bytesSent += length; } } diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageReader.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageReader.java similarity index 93% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageReader.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageReader.java index b3230418755..b97eb28b1ca 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/message/MessageReader.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageReader.java @@ -16,13 +16,12 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common.message; +package org.eclipse.jetty.websocket.util.messages; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.websocket.common.MessageSink; import org.eclipse.jetty.websocket.core.Frame; /** diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/MessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageSink.java similarity index 96% rename from jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/MessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageSink.java index 4b254b94298..d1b5842d2c5 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/MessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageSink.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.common; +package org.eclipse.jetty.websocket.util.messages; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.websocket.core.Frame; diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriter.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageWriter.java similarity index 95% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriter.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageWriter.java index a69f68ba6a9..ddc2b85fbef 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/MessageWriter.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageWriter.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.IOException; import java.io.Writer; @@ -25,6 +25,7 @@ import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; +import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; @@ -56,10 +57,10 @@ public class MessageWriter extends Writer private Callback callback; private boolean closed; - public MessageWriter(CoreSession coreSession, int bufferSize) + public MessageWriter(CoreSession coreSession, ByteBufferPool bufferPool) { this.coreSession = coreSession; - this.buffer = CharBuffer.allocate(bufferSize); + this.buffer = CharBuffer.allocate(coreSession.getOutputBufferSize()); this.frame = new Frame(OpCode.TEXT); } @@ -219,4 +220,4 @@ public class MessageWriter extends Writer callback.failed(failure); } } -} +} \ No newline at end of file diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteArrayMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteArrayMessageSink.java similarity index 84% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteArrayMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteArrayMessageSink.java index 3bc62aac5aa..62e6bfe8f2a 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteArrayMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteArrayMessageSink.java @@ -16,26 +16,24 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.nio.ByteBuffer; -import java.util.Objects; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; -import org.eclipse.jetty.websocket.javax.common.util.InvalidSignatureException; +import org.eclipse.jetty.websocket.util.InvalidSignatureException; public class PartialByteArrayMessageSink extends AbstractMessageSink { - public PartialByteArrayMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public PartialByteArrayMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); - Objects.requireNonNull(methodHandle, "MethodHandle"); // byte[] buf, int offset, int length MethodType onMessageType = MethodType.methodType(Void.TYPE, byte[].class, int.class, int.class, boolean.class); if (methodHandle.type() != onMessageType) @@ -66,7 +64,6 @@ public class PartialByteArrayMessageSink extends AbstractMessageSink } methodHandle.invoke(buffer, offset, length, frame.isFin()); - callback.succeeded(); } catch (Throwable t) diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteBufferMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteBufferMessageSink.java similarity index 79% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteBufferMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteBufferMessageSink.java index 6be01d31b69..70cf34b8376 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialByteBufferMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialByteBufferMessageSink.java @@ -16,21 +16,29 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; public class PartialByteBufferMessageSink extends AbstractMessageSink { - public PartialByteBufferMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public PartialByteBufferMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); + + /* TODO: Review + MethodType onMessageType = MethodType.methodType(Void.TYPE, ByteBuffer.class, boolean.class); + if (methodHandle.type() != onMessageType) + { + throw InvalidSignatureException.build(onMessageType, methodHandle.type()); + } + */ } @SuppressWarnings("Duplicates") diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialStringMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialStringMessageSink.java similarity index 93% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialStringMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialStringMessageSink.java index d0f8394df38..c6451482f15 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/PartialStringMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/PartialStringMessageSink.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; import java.nio.ByteBuffer; @@ -27,8 +27,8 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; public class PartialStringMessageSink extends AbstractMessageSink { @@ -36,7 +36,7 @@ public class PartialStringMessageSink extends AbstractMessageSink private Utf8StringBuilder utf; private int size; - public PartialStringMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public PartialStringMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); Objects.requireNonNull(methodHandle, "MethodHandle"); diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ReaderMessageSink.java similarity index 83% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ReaderMessageSink.java index 86ec3c9c690..7cfeb14f7b6 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/ReaderMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/ReaderMessageSink.java @@ -16,17 +16,17 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.io.Reader; import java.lang.invoke.MethodHandle; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; public class ReaderMessageSink extends DispatchedMessageSink { - public ReaderMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public ReaderMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); } diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/StringMessageSink.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/StringMessageSink.java similarity index 84% rename from jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/StringMessageSink.java rename to jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/StringMessageSink.java index c4e24cc96a8..5be932fc595 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/messages/StringMessageSink.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/StringMessageSink.java @@ -16,7 +16,7 @@ // ======================================================================== // -package org.eclipse.jetty.websocket.javax.common.messages; +package org.eclipse.jetty.websocket.util.messages; import java.lang.invoke.MethodHandle; import java.nio.ByteBuffer; @@ -26,9 +26,9 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; +import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.exception.MessageTooLargeException; -import org.eclipse.jetty.websocket.javax.common.JavaxWebSocketSession; public class StringMessageSink extends AbstractMessageSink { @@ -36,7 +36,7 @@ public class StringMessageSink extends AbstractMessageSink private Utf8StringBuilder utf; private int size; - public StringMessageSink(JavaxWebSocketSession session, MethodHandle methodHandle) + public StringMessageSink(CoreSession session, MethodHandle methodHandle) { super(session, methodHandle); this.size = 0; @@ -53,10 +53,11 @@ public class StringMessageSink extends AbstractMessageSink ByteBuffer payload = frame.getPayload(); size += payload.remaining(); - if (session.getMaxTextMessageBufferSize() > 0 && size > session.getMaxTextMessageBufferSize()) + long maxTextMessageSize = session.getMaxTextMessageSize(); + if (maxTextMessageSize > 0 && size > maxTextMessageSize) { - throw new MessageTooLargeException(String.format("Binary message too large: (actual) %,d > (configured max text buffer size) %,d", - size, session.getMaxTextMessageBufferSize())); + throw new MessageTooLargeException(String.format("Text message too large: (actual) %,d > (configured max text message size) %,d", + size, maxTextMessageSize)); } if (utf == null) diff --git a/jetty-websocket/websocket-util/src/test/resources/jetty-logging.properties b/jetty-websocket/websocket-util/src/test/resources/jetty-logging.properties new file mode 100644 index 00000000000..07faa86dbce --- /dev/null +++ b/jetty-websocket/websocket-util/src/test/resources/jetty-logging.properties @@ -0,0 +1 @@ +org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog \ No newline at end of file From 9dd8a53a6d3a125b30eaddb58af62f9050d06cb0 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Wed, 19 Feb 2020 19:20:04 +0100 Subject: [PATCH 21/27] Work in progress on review comments Signed-off-by: Greg Wilkins --- .../eclipse/jetty/xml/XmlConfiguration.java | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index 4e38c478550..fbb8b6c60e5 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -414,7 +414,7 @@ public class XmlConfiguration { try { - obj = construct(oClass, new NamedArgs(null, oClass, XmlConfiguration.getNodes(_root, "Arg"))); + obj = construct(oClass, new Args(null, oClass, XmlConfiguration.getNodes(_root, "Arg"))); } catch (NoSuchMethodException x) { @@ -910,7 +910,7 @@ public class XmlConfiguration try { - Object nobj = call(oClass, name, obj, new NamedArgs(obj, oClass, aoeNode.getNodes("Arg"))); + Object nobj = call(oClass, name, obj, new Args(obj, oClass, aoeNode.getNodes("Arg"))); if (id != null) _configuration.getIdMap().put(id, nobj); configure(nobj, node, aoeNode.getNext()); @@ -922,7 +922,7 @@ public class XmlConfiguration } } - private Object call(Class oClass, String methodName, Object obj, NamedArgs args) throws InvocationTargetException, NoSuchMethodException + private Object call(Class oClass, String methodName, Object obj, Args args) throws InvocationTargetException, NoSuchMethodException { Objects.requireNonNull(oClass, "Class cannot be null"); Objects.requireNonNull(methodName, "Method name cannot be null"); @@ -976,7 +976,7 @@ public class XmlConfiguration Object nobj; try { - nobj = construct(oClass, new NamedArgs(obj, oClass, aoeNode.getNodes("Arg"))); + nobj = construct(oClass, new Args(obj, oClass, aoeNode.getNodes("Arg"))); } catch (NoSuchMethodException e) { @@ -991,12 +991,11 @@ public class XmlConfiguration return nobj; } - private Object construct(Class klass, NamedArgs args) throws InvocationTargetException, NoSuchMethodException + private Object construct(Class klass, Args args) throws InvocationTargetException, NoSuchMethodException { Objects.requireNonNull(klass, "Class cannot be null"); Objects.requireNonNull(args, "Named list cannot be null"); - constructors: for (Constructor constructor : klass.getConstructors()) { try @@ -1650,13 +1649,13 @@ public class XmlConfiguration } } - private class NamedArgs + private class Args { - final Class _class; - final List _arguments; - final List _names; + private final Class _class; + private final List _arguments; + private final List _names; - NamedArgs(Object obj, Class oClass, List args) throws Exception + private Args(Object obj, Class oClass, List args) throws Exception { _class = oClass; _arguments = new ArrayList<>(); @@ -1668,7 +1667,7 @@ public class XmlConfiguration } } - private NamedArgs(List arguments, List names) + private Args(List arguments, List names) { _class = null; _arguments = arguments; @@ -1691,11 +1690,11 @@ public class XmlConfiguration if (executable instanceof Constructor) _class.getConstructor(types); else - _class.getMethod(((Method)executable).getName(), types); + _class.getMethod(executable.getName(), types); } catch (NoSuchMethodException e) { - // There is not a no varArgs alternative so let's try a null varArgs match + // There is not a no varArgs alternative so let's try a an empty varArgs match args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); } catch (Exception e) @@ -1707,13 +1706,13 @@ public class XmlConfiguration return args; } - NamedArgs asEmptyVarArgs(Class varArgType) + Args asEmptyVarArgs(Class varArgType) { List arguments = new ArrayList<>(_arguments); arguments.add(Array.newInstance(varArgType.getComponentType(), 0)); List names = new ArrayList<>(_names); names.add(null); - return new NamedArgs(arguments, names); + return new Args(arguments, names); } Object[] matchArgsToParameters(Executable executable) From 0c8860f1313804916fa6e21dd619e38b3865ca59 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Wed, 19 Feb 2020 19:35:52 +0100 Subject: [PATCH 22/27] Sort the executables so that non varargs variants are tried before empty var args. Signed-off-by: Greg Wilkins --- .../eclipse/jetty/xml/XmlConfiguration.java | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index fbb8b6c60e5..3ca8f30b39d 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -41,6 +41,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -98,6 +99,22 @@ public class XmlConfiguration }; private static final Iterable __factoryLoader = ServiceLoader.load(ConfigurationProcessorFactory.class); private static final XmlParser __parser = initParser(); + public static final Comparator EXECUTABLE_COMPARATOR = (o1, o2) -> + { + int p1 = o1.getParameterCount(); + int p2 = o2.getParameterCount(); + int compare = Integer.compare(p1, p2); + if (compare == 0 && p1 > 0) + { + boolean a1 = o1.getParameterTypes()[p1 - 1].isArray(); + boolean a2 = o2.getParameterTypes()[p2 - 1].isArray(); + if (a1 && !a2) + compare = 1; + else if (!a1 && a2) + compare = -1; + } + return compare; + }; private static XmlParser initParser() { @@ -930,7 +947,10 @@ public class XmlConfiguration throw new IllegalArgumentException("Method name cannot be blank"); // Lets just try all methods for now - for (Method method : oClass.getMethods()) + + Method[] methods = oClass.getMethods(); + Arrays.sort(methods, EXECUTABLE_COMPARATOR); + for (Method method : methods) { if (!method.getName().equals(methodName)) continue; @@ -996,7 +1016,9 @@ public class XmlConfiguration Objects.requireNonNull(klass, "Class cannot be null"); Objects.requireNonNull(args, "Named list cannot be null"); - for (Constructor constructor : klass.getConstructors()) + Constructor[] constructors = klass.getConstructors(); + Arrays.sort(constructors, EXECUTABLE_COMPARATOR); + for (Constructor constructor : constructors) { try { @@ -1683,24 +1705,8 @@ public class XmlConfiguration int count = executable.getParameterCount(); if (count > 0 && executable.getParameterTypes()[count - 1].isArray()) { - try - { - // Does a non varargs method exist? - Class[] types = Arrays.copyOf(executable.getParameterTypes(), count - 1); - if (executable instanceof Constructor) - _class.getConstructor(types); - else - _class.getMethod(executable.getName(), types); - } - catch (NoSuchMethodException e) - { - // There is not a no varArgs alternative so let's try a an empty varArgs match - args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); - } - catch (Exception e) - { - LOG.ignore(e); - } + // There is not a no varArgs alternative so let's try a an empty varArgs match + args = asEmptyVarArgs(executable.getParameterTypes()[count - 1]).matchArgsToParameters(executable); } } return args; From b46b25b450647311e5d4ad6f30c463ca05f84616 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Wed, 19 Feb 2020 22:38:58 +0100 Subject: [PATCH 23/27] release buffer on overflow Signed-off-by: Greg Wilkins --- .../main/java/org/eclipse/jetty/server/HttpConnection.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java index 26f7cb550db..b23c5cd0c94 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java @@ -763,9 +763,10 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http case HEADER_OVERFLOW: { - if (_header.capacity() >= _config.getResponseHeaderSize()) - throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large"); + int capacity = _header.capacity(); _bufferPool.release(_header); + if (capacity >= _config.getResponseHeaderSize()) + throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Response header too large"); _header = _bufferPool.acquire(_config.getResponseHeaderSize(), HEADER_BUFFER_DIRECT); continue; } From 422b32be9e6673aaf9436e9ba79f58b0a129d429 Mon Sep 17 00:00:00 2001 From: olivier lamy Date: Thu, 20 Feb 2020 10:33:50 +1000 Subject: [PATCH 24/27] Revert "Issue #4562 remove deprecated jetty-runner (#4563)" This reverts commit ebed3e5b38309b90f86f03fa3ec6c2473e1087f0. --- .../asciidoc/distribution-guide/index.adoc | 1 + .../distribution-guide/runner/chapter.adoc | 24 + .../runner/jetty-runner.adoc | 349 ++++++++++ jetty-runner/pom.xml | 135 ++++ jetty-runner/src/it/settings.xml | 36 ++ .../it/test-jar-manifest/invoker.properties | 1 + jetty-runner/src/it/test-jar-manifest/pom.xml | 59 ++ .../src/it/test-jar-manifest/postbuild.groovy | 10 + .../java/org/eclipse/jetty/runner/Runner.java | 595 ++++++++++++++++++ .../eclipse/jetty/runner/package-info.java | 23 + jetty-runner/src/main/resources/MANIFEST.MF | 1 + pom.xml | 1 + 12 files changed, 1235 insertions(+) create mode 100644 jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc create mode 100644 jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc create mode 100644 jetty-runner/pom.xml create mode 100644 jetty-runner/src/it/settings.xml create mode 100644 jetty-runner/src/it/test-jar-manifest/invoker.properties create mode 100644 jetty-runner/src/it/test-jar-manifest/pom.xml create mode 100644 jetty-runner/src/it/test-jar-manifest/postbuild.groovy create mode 100644 jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java create mode 100644 jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java create mode 100644 jetty-runner/src/main/resources/MANIFEST.MF diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc index 679a3217a41..20a8c1a9022 100644 --- a/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc +++ b/jetty-documentation/src/main/asciidoc/distribution-guide/index.adoc @@ -74,4 +74,5 @@ include::jndi/chapter.adoc[] include::alpn/chapter.adoc[] include::fastcgi/chapter.adoc[] include::extras/chapter.adoc[] +include::runner/chapter.adoc[] include::tuning/chapter.adoc[] diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc new file mode 100644 index 00000000000..946b526331b --- /dev/null +++ b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/chapter.adoc @@ -0,0 +1,24 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under +// the terms of the Eclipse Public License 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0 +// +// This Source Code may also be made available under the following +// Secondary Licenses when the conditions for such availability set +// forth in the Eclipse Public License, v. 2.0 are satisfied: +// the Apache License v2.0 which is available at +// https://www.apache.org/licenses/LICENSE-2.0 +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +[[runner]] +== Jetty Runner + +This chapter explains how to use the `jetty-runner` to run your webapps without needing an installation of Jetty. + +include::jetty-runner.adoc[] diff --git a/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc new file mode 100644 index 00000000000..e0f36400658 --- /dev/null +++ b/jetty-documentation/src/main/asciidoc/distribution-guide/runner/jetty-runner.adoc @@ -0,0 +1,349 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under +// the terms of the Eclipse Public License 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0 +// +// This Source Code may also be made available under the following +// Secondary Licenses when the conditions for such availability set +// forth in the Eclipse Public License, v. 2.0 are satisfied: +// the Apache License v2.0 which is available at +// https://www.apache.org/licenses/LICENSE-2.0 +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +[[jetty-runner]] +=== Use Jetty Without an Installed Distribution + +The idea of the `jetty-runner` is extremely simple – run a webapp directly from the command line using a single jar file and as much default configuration as possible. +Of course, if your webapp is not as straightforward, the `jetty-runner` has command line options which allow you to customize the execution environment. + +[[jetty-runner-preparation]] +==== Preparation + +You will need the `jetty-runner` jar: + +1. Download the `jetty-runner` jar available at https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-runner/[Maven Central]. + +==== Deploying a Simple Context + +Let's assume we have a very simple webapp that does not need any resources from its environment, nor any configuration apart from the defaults. +Starting it is as simple as performing the following: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar simple.war +.... + +This will start Jetty on port 8080, and deploy the webapp to `/`. + +Your webapp does not have to be packed into a war, you can deploy a webapp that is a directory instead in the same way: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar simple +.... + +In fact, the webapp does not have to be a war or even a directory, it can simply be a Jetty link:#using-context-provider[context xml] file that describes your webapp: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar simple-context.xml +.... + +____ +[NOTE] +When using a context xml file, the application being deployed is not even required to be a fully-fledged webapp. +It can simply be a Jetty link:#what-is-a-context[context]. +____ + +By default, `jetty-runner` implements all Configuration Classes so that users can set up and deploy new instances with as little configuration as possible. +If you wish to only implement certain Configuration Classes, they will need to be defined in the context xml for the webapp/context. +The default Configuration Classes are: + +`org.eclipse.jetty.webapp.WebInfConfiguration` +`org.eclipse.jetty.webapp.WebXmlConfiguration` +`org.eclipse.jetty.webapp.MetaInfConfiguration` +`org.eclipse.jetty.webapp.FragmentConfiguration` +`org.eclipse.jetty.webapp.JettyWebXmlConfiguration` +`org.eclipse.jetty.plus.webapp.EnvConfiguration` +`org.eclipse.jetty.plus.webapp.PlusConfiguration` +`org.eclipse.jetty.annotations.AnnotationConfiguration` + +You can learn more about implementing specific Configuration Classes link:https://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-configurations[here.] + +==== Deploying Multiple Contexts + +If you have more than one webapp that must be deployed, simply provide them all on the command line. +You can control the context paths for them using the `--path` parameter. +Here's an example of deploying 2 wars (although either or both of them could be unpacked directories instead): + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --path /one my1.war --path /two my2.war +.... + +If you have context xml files that describe your webapps, you can fully configure your webapps in them and hence you won't need to use the command line switches. +Just provide the list of context files like so: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar my-first-context.xml my-second-context.xml my-third-context.xml +.... + +____ +[NOTE] +Switched used on the command line override configuration file settings. +So, for example, you could set the context path for the webapp inside the context xml file, and use the `--path` switch to override it on the command line. +____ + + +===== Changing the Default Port + +By default the `jetty-runner` will listen on port 8080. +You can easily change this on the command line using the `--port` command. +Here's an example that runs our simple.war on port 9090: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --port 9090 simple.war +.... + +===== Using jetty.xml Files + +Instead of, or in addition to, using command line switches, you can use one or more `jetty.xml` files to configure the environment for your webapps. +Here's an example where we apply two different `jetty.xml` files: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --config jetty.xml --config jetty-https.xml simple.war +.... + +[[runner-configuration-reference]] +==== Full Configuration Reference + +You can see the fill set of configuration options using the `--help` switch: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --help +.... + +Here's what the output will look like: + +[source, plain, subs="{sub-order}"] +---- + +Usage: java [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] +Server opts: + --version - display version and exit + --log file - request log filename (with optional 'yyyy_mm_dd' wildcard + --out file - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard + --host name|ip - interface to listen on (default is all interfaces) + --port n - port to listen on (default 8080) + --stop-port n - port to listen for stop command (or -DSTOP.PORT=n) + --stop-key n - security string for stop command (required if --stop-port is present) (or -DSTOP.KEY=n) + [--jar file]*n - each tuple specifies an extra jar to be added to the classloader + [--lib dir]*n - each tuple specifies an extra directory of jars to be added to the classloader + [--classes dir]*n - each tuple specifies an extra directory of classes to be added to the classloader + --stats [unsecure|realm.properties] - enable stats gathering servlet context + [--config file]*n - each tuple specifies the name of a jetty xml config file to apply (in the order defined) +Context opts: + [[--path /path] context]*n - WAR file, web app dir or context xml file, optionally with a context path +---- + +===== Printing the Version +Print out the version of Jetty and then exit immediately. + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --version +.... + +===== Configuring a Request Log +Cause Jetty to write a request log with the given name. +If the file is prefixed with `yyyy_mm_dd` then the file will be automatically rolled over. +Note that for finer grained configuration of the link:{JDURL}/org/eclipse/jetty/server/NCSARequestLog.html[request log], you will need to use a Jetty xml file instead. + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --log yyyy_mm_dd-requests.log my.war +.... + +===== Configuring the Output Log +Redirect the output of jetty logging to the named file. +If the file is prefixed with `yyyy_mm_dd` then the file will be automatically rolled over. + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --out yyyy_mm_dd-output.log my.war +.... + +===== Configuring the Interface for HTTP +Like Jetty standalone, the default is for the connectors to listen on all interfaces on a machine. +You can control that by specifying the name or ip address of the particular interface you wish to use with the `--host` argument: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --host 192.168.22.19 my.war +.... + +===== Configuring the Port for HTTP +The default port number is 8080. +To link:#how-to-configure-connectors[configure a https connector], use a Jetty xml config file instead. + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --port 9090 my.war +.... + +===== Configuring Stop +You can configure a port number for Jetty to listen on for a stop command, so you are able to stop it from a different terminal. +This requires the use of a "secret" key, to prevent malicious or accidental termination. +Use the `--stop-port` and `--stop-key` (or `-DSTOP.PORT=` and `-DSTOP.KEY=`, respectively) parameters as arguments to the `jetty-runner`: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --stop-port 8181 --stop-key abc123 +.... + +Then, to stop Jetty from a different terminal, you need to supply the same port and key information. +For this you'll either need a local installation of Jetty, the link:#jetty-maven-plugin[jetty-maven-plugin], the link:#jetty-ant[jetty-ant plugin], or a custom class. +Here's how to use a Jetty installation to perform a stop: + +[source, screen, subs="{sub-order}"] +.... +> java -jar start.jar -DSTOP.PORT=8181 -DSTOP.KEY=abc123 --stop +.... + +===== Configuring the Container Classpath +With a local installation of Jetty, you add jars and classes to the container's classpath by putting them in the `{$jetty.base}/lib` directory. +With the `jetty-runner`, you can use the `--lib`, `--jar` and `--classes` arguments instead to achieve the same thing. + +`--lib` adds the location of a directory which contains jars to add to the container classpath. +You can add 1 or more. +Here's an example of configuring 2 directories: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --lib /usr/local/external/lib --lib $HOME/external-other/lib my.war +.... + +`--jar` adds a single jar file to the container classpath. +You can add 1 or more. +Here's an example of configuring 3 extra jars: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --jar /opt/stuff/jars/jar1.jar --jar $HOME/jars/jar2.jar --jar /usr/local/proj/jars/jar3.jar my.war +.... + +`--classes` add the location of a directory containing classes to add to the container classpath. +You can add 1 or more. +Here's an example of configuring a single extra classes dir: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --classes /opt/stuff/classes my.war +.... + +____ +[NOTE] +When using the `--jar` and/or `--lib` arguments, by default these will *not* be inspected for `META-INF` information such as `META-INF/resources`, `META-INF/web-fragment.xml`, or `META-INF/taglib.tld`. +If you require these jar files inspected you will need to define the link:https://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-context-attributes[jar pattern in your context xml file]. +Jetty-Runner automatically provides and appends a suitable pattern for jtsl taglibs (this pattern is different than the one in the standard Jetty distribution). +____ + + +===== Gathering Statistics +If statistics gathering is enabled, then they are viewable by surfing to the context `/stats`. +You may optionally protect access to that context with a password. +Here's an example of enabling statistics, with no password protection: + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --stats unsecure my.war +.... + +If we wished to protect access to the `/stats` context, we would provide the location of a Jetty realm configuration file containing authentication and authorization information. +For example, we could use the following example realm file from the Jetty distribution: + +[source, screen, subs="{sub-order}"] +.... +jetty: MD5:164c88b302622e17050af52c89945d44,user +admin: CRYPT:adpexzg3FUZAk,server-administrator,content-administrator,admin +other: OBF:1xmk1w261u9r1w1c1xmq,user +plain: plain,user +user: password,user +# This entry is for digest auth. The credential is a MD5 hash of username:realmname:password +digest: MD5:6e120743ad67abfbc385bc2bb754e297,user +.... + +Assuming we've copied it into the local directory, we would apply it like so + +[source, screen, subs="{sub-order}"] +.... +> java -jar jetty-runner.jar --stats realm.properties my.war +.... + +After navigating to http://localhost:8080/ a few times, we can point to the stats servlet on http://localhost:8080/stats to see the output: + +.... +Statistics: +Statistics gathering started 1490627ms ago + +Requests: +Total requests: 9 +Active requests: 1 +Max active requests: 1 +Total requests time: 63 +Mean request time: 7.875 +Max request time: 26 +Request time standard deviation: 8.349764752888037 + + +Dispatches: +Total dispatched: 9 +Active dispatched: 1 +Max active dispatched: 1 +Total dispatched time: 63 +Mean dispatched time: 7.875 +Max dispatched time: 26 +Dispatched time standard deviation: 8.349764752888037 +Total requests suspended: 0 +Total requests expired: 0 +Total requests resumed: 0 + + +Responses: +1xx responses: 0 +2xx responses: 7 +3xx responses: 1 +4xx responses: 0 +5xx responses: 0 +Bytes sent total: 1453 + + +Connections: +org.eclipse.jetty.server.ServerConnector@203822411 +Protocols:http/1.1 +Statistics gathering started 1490606ms ago +Total connections: 7 +Current connections open: 1 +Max concurrent connections open: 2 +Total connections duration: 72883 +Mean connection duration: 12147.166666666666 +Max connection duration: 65591 +Connection duration standard deviation: 23912.40292977684 +Total messages in: 7 +Total messages out: 7 + + +Memory: +Heap memory usage: 49194840 bytes +Non-heap memory usage: 12611696 bytes +.... diff --git a/jetty-runner/pom.xml b/jetty-runner/pom.xml new file mode 100644 index 00000000000..96a76bed6f8 --- /dev/null +++ b/jetty-runner/pom.xml @@ -0,0 +1,135 @@ + + + org.eclipse.jetty + jetty-project + 10.0.0-SNAPSHOT + + 4.0.0 + jetty-runner + Jetty :: Runner + + + target/distribution + ${project.groupId}.runner + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack-dependencies + prepare-package + + unpack-dependencies + + + ** + **/MANIFEST.MF,META-INF/*.RSA,META-INF/*.DSA,META-INF/*.SF,module-info.class + ${project.build.directory}/classes + false + true + + + + + + org.apache.maven.plugins + maven-invoker-plugin + + + integration-test + integration-test + + install + integration-test + verify + + + + + + ${maven.dependency.plugin.version} + + + clean + + + + + + + + org.neo4j.build.plugins + clirr-maven-plugin + + + true + + + + org.apache.felix + maven-bundle-plugin + + + true + + ${project.build.directory}/NON_USED_MANIFEST + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/MANIFEST.MF + + org.eclipse.jetty.runner.Runner + + + + + + + + + + + org.eclipse.jetty + jetty-plus + ${project.version} + + + org.eclipse.jetty + jetty-annotations + ${project.version} + + + org.eclipse.jetty + jetty-jaas + ${project.version} + + + org.eclipse.jetty.websocket + websocket-jetty-server + ${project.version} + + + org.eclipse.jetty + jetty-jndi + ${project.version} + + + org.eclipse.jetty + apache-jsp + ${project.version} + + + org.eclipse.jetty + apache-jstl + ${project.version} + + + diff --git a/jetty-runner/src/it/settings.xml b/jetty-runner/src/it/settings.xml new file mode 100644 index 00000000000..d64bdb89034 --- /dev/null +++ b/jetty-runner/src/it/settings.xml @@ -0,0 +1,36 @@ + + + + + + it-repo + + true + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + + diff --git a/jetty-runner/src/it/test-jar-manifest/invoker.properties b/jetty-runner/src/it/test-jar-manifest/invoker.properties new file mode 100644 index 00000000000..86f8ef2b751 --- /dev/null +++ b/jetty-runner/src/it/test-jar-manifest/invoker.properties @@ -0,0 +1 @@ +invoker.goals = generate-resources diff --git a/jetty-runner/src/it/test-jar-manifest/pom.xml b/jetty-runner/src/it/test-jar-manifest/pom.xml new file mode 100644 index 00000000000..d619f71a186 --- /dev/null +++ b/jetty-runner/src/it/test-jar-manifest/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + org.eclipse.jetty.its + jetty-runner-it-test + 1.0.0-SNAPSHOT + war + + + UTF-8 + + + + + + org.eclipse.jetty + jetty-runner + @project.version@ + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + @maven.dependency.plugin.version@ + + + copy-jetty-runner + generate-resources + + copy + + + + + org.eclipse.jetty + jetty-runner + @project.version@ + jar + false + ${project.build.directory}/ + jetty-runner.jar + + + false + true + + + + + + + + diff --git a/jetty-runner/src/it/test-jar-manifest/postbuild.groovy b/jetty-runner/src/it/test-jar-manifest/postbuild.groovy new file mode 100644 index 00000000000..da1a6d99e3c --- /dev/null +++ b/jetty-runner/src/it/test-jar-manifest/postbuild.groovy @@ -0,0 +1,10 @@ +import java.util.jar.* + +File artifact = new File( basedir, "target/jetty-runner.jar" ) +assert artifact.exists() + +JarFile jar = new JarFile( artifact ); + +Attributes manifest = jar.getManifest().getMainAttributes(); + +assert manifest.getValue( new Attributes.Name( "Main-Class" ) ).equals( "org.eclipse.jetty.runner.Runner" ) diff --git a/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java b/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java new file mode 100644 index 00000000000..991fc300257 --- /dev/null +++ b/jetty-runner/src/main/java/org/eclipse/jetty/runner/Runner.java @@ -0,0 +1,595 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under +// the terms of the Eclipse Public License 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0 +// +// This Source Code may also be made available under the following +// Secondary Licenses when the conditions for such availability set +// forth in the Eclipse Public License, v. 2.0 are satisfied: +// the Apache License v2.0 which is available at +// https://www.apache.org/licenses/LICENSE-2.0 +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +package org.eclipse.jetty.runner; + +import java.io.IOException; +import java.io.PrintStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import org.eclipse.jetty.io.ConnectionStatistics; +import org.eclipse.jetty.security.ConstraintMapping; +import org.eclipse.jetty.security.ConstraintSecurityHandler; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.security.authentication.BasicAuthenticator; +import org.eclipse.jetty.server.AbstractConnector; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.CustomRequestLog; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.ShutdownMonitor; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.server.handler.DefaultHandler; +import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.server.handler.StatisticsHandler; +import org.eclipse.jetty.server.session.SessionHandler; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.servlet.StatisticsServlet; +import org.eclipse.jetty.util.RolloverFileOutputStream; +import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.log.Log; +import org.eclipse.jetty.util.log.Logger; +import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.security.Constraint; +import org.eclipse.jetty.webapp.MetaInfConfiguration; +import org.eclipse.jetty.webapp.WebAppContext; +import org.eclipse.jetty.xml.XmlConfiguration; + +/** + * Runner + *

    + * Combine jetty classes into a single executable jar and run webapps based on the args to it. + * + * @deprecated No replacement provided or available. Migrate to jetty-home (and use {@code ${jetty.base}} directory). + */ +@Deprecated +public class Runner +{ + private static final Logger LOG = Log.getLogger(Runner.class); + + public static final String[] PLUS_CONFIGURATION_CLASSES = + { + org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), + org.eclipse.jetty.annotations.AnnotationConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName() + }; + public static final String CONTAINER_INCLUDE_JAR_PATTERN = ".*/jetty-runner-[^/]*\\.jar$"; + public static final String DEFAULT_CONTEXT_PATH = "/"; + public static final int DEFAULT_PORT = 8080; + + protected Server _server; + protected URLClassLoader _classLoader; + protected Classpath _classpath = new Classpath(); + protected ContextHandlerCollection _contexts; + protected String _logFile; + protected ArrayList _configFiles; + protected boolean _enableStats = false; + protected String _statsPropFile; + + /** + * Classpath + */ + public class Classpath + { + private List _classpath = new ArrayList<>(); + + public void addJars(Resource lib) throws IOException + { + if (lib == null || !lib.exists()) + throw new IllegalStateException("No such lib: " + lib); + + String[] list = lib.list(); + if (list == null) + return; + + for (String path : list) + { + if (".".equals(path) || "..".equals(path)) + continue; + + try (Resource item = lib.addPath(path)) + { + if (item.isDirectory()) + addJars(item); + else + { + String lowerCasePath = path.toLowerCase(Locale.ENGLISH); + if (lowerCasePath.endsWith(".jar") || + lowerCasePath.endsWith(".zip")) + { + _classpath.add(item.getURI()); + } + } + } + } + } + + public void addPath(Resource path) + { + if (path == null || !path.exists()) + throw new IllegalStateException("No such path: " + path); + _classpath.add(path.getURI()); + } + + public URI[] asArray() + { + return _classpath.toArray(new URI[0]); + } + } + + public Runner() + { + } + + /** + * Generate helpful usage message and exit + * + * @param error the error header + */ + public void usage(String error) + { + if (error != null) + System.err.println("ERROR: " + error); + System.err.println("Usage: java [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...] "); + System.err.println("Server opts:"); + System.err.println(" --version - display version and exit"); + System.err.println(" --log file - request log filename (with optional 'yyyy_mm_dd' wildcard"); + System.err.println(" --out file - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard"); + System.err.println(" --host name|ip - interface to listen on (default is all interfaces)"); + System.err.println(" --port n - port to listen on (default 8080)"); + System.err.println(" --stop-port n - port to listen for stop command (or -DSTOP.PORT=n)"); + System.err.println(" --stop-key n - security string for stop command (required if --stop-port is present) (or -DSTOP.KEY=n)"); + System.err.println(" [--jar file]*n - each tuple specifies an extra jar to be added to the classloader"); + System.err.println(" [--lib dir]*n - each tuple specifies an extra directory of jars to be added to the classloader"); + System.err.println(" [--classes dir]*n - each tuple specifies an extra directory of classes to be added to the classloader"); + System.err.println(" --stats [unsecure|realm.properties] - enable stats gathering servlet context"); + System.err.println(" [--config file]*n - each tuple specifies the name of a jetty xml config file to apply (in the order defined)"); + System.err.println("Context opts:"); + System.err.println(" [[--path /path] context]*n - WAR file, web app dir or context xml file, optionally with a context path"); + System.exit(1); + } + + /** + * Generate version message and exit + */ + public void version() + { + System.err.println("org.eclipse.jetty.runner.Runner: " + Server.getVersion()); + System.exit(1); + } + + /** + * Configure a jetty instance and deploy the webapps presented as args + * + * @param args the command line arguments + * @throws Exception if unable to configure + */ + public void configure(String[] args) throws Exception + { + // handle classpath bits first so we can initialize the log mechanism. + for (int i = 0; i < args.length; i++) + { + if ("--lib".equals(args[i])) + { + try (Resource lib = Resource.newResource(args[++i])) + { + if (!lib.exists() || !lib.isDirectory()) + usage("No such lib directory " + lib); + _classpath.addJars(lib); + } + } + else if ("--jar".equals(args[i])) + { + try (Resource jar = Resource.newResource(args[++i])) + { + if (!jar.exists() || jar.isDirectory()) + usage("No such jar " + jar); + _classpath.addPath(jar); + } + } + else if ("--classes".equals(args[i])) + { + try (Resource classes = Resource.newResource(args[++i])) + { + if (!classes.exists() || !classes.isDirectory()) + usage("No such classes directory " + classes); + _classpath.addPath(classes); + } + } + else if (args[i].startsWith("--")) + i++; + } + + initClassLoader(); + + LOG.info("Runner"); + LOG.debug("Runner classpath {}", _classpath); + + String contextPath = DEFAULT_CONTEXT_PATH; + boolean contextPathSet = false; + int port = DEFAULT_PORT; + String host = null; + int stopPort = Integer.getInteger("STOP.PORT", 0); + String stopKey = System.getProperty("STOP.KEY", null); + + boolean runnerServerInitialized = false; + + for (int i = 0; i < args.length; i++) + { + switch (args[i]) + { + case "--port": + port = Integer.parseInt(args[++i]); + break; + case "--host": + host = args[++i]; + break; + case "--stop-port": + stopPort = Integer.parseInt(args[++i]); + break; + case "--stop-key": + stopKey = args[++i]; + break; + case "--log": + _logFile = args[++i]; + break; + case "--out": + String outFile = args[++i]; + PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1)); + LOG.info("Redirecting stderr/stdout to " + outFile); + System.setErr(out); + System.setOut(out); + break; + case "--path": + contextPath = args[++i]; + contextPathSet = true; + break; + case "--config": + if (_configFiles == null) + _configFiles = new ArrayList<>(); + _configFiles.add(args[++i]); + break; + case "--lib": + ++i;//skip + + break; + case "--jar": + ++i; //skip + + break; + case "--classes": + ++i;//skip + + break; + case "--stats": + _enableStats = true; + _statsPropFile = args[++i]; + _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); + break; + default: + // process system property type argument so users can use in second args part + if (args[i].startsWith("-D")) + { + String[] sysProps = args[i].substring(2).split("=", 2); + if ("STOP.KEY".equals(sysProps[0])) + { + stopKey = sysProps[1]; + break; + } + else if ("STOP.PORT".equals(sysProps[0])) + { + stopPort = Integer.parseInt(sysProps[1]); + break; + } + } + +// process contexts + + if (!runnerServerInitialized) // log handlers not registered, server maybe not created, etc + { + if (_server == null) // server not initialized yet + { + // build the server + _server = new Server(); + } + + //apply jetty config files if there are any + if (_configFiles != null) + { + for (String cfg : _configFiles) + { + try (Resource resource = Resource.newResource(cfg)) + { + XmlConfiguration xmlConfiguration = new XmlConfiguration(resource); + xmlConfiguration.configure(_server); + } + } + } + + //check that everything got configured, and if not, make the handlers + HandlerCollection handlers = (HandlerCollection)_server.getChildHandlerByClass(HandlerCollection.class); + if (handlers == null) + { + handlers = new HandlerCollection(); + _server.setHandler(handlers); + } + + //check if contexts already configured + _contexts = (ContextHandlerCollection)handlers.getChildHandlerByClass(ContextHandlerCollection.class); + if (_contexts == null) + { + _contexts = new ContextHandlerCollection(); + prependHandler(_contexts, handlers); + } + + if (_enableStats) + { + //if no stats handler already configured + if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) + { + StatisticsHandler statsHandler = new StatisticsHandler(); + + Handler oldHandler = _server.getHandler(); + statsHandler.setHandler(oldHandler); + _server.setHandler(statsHandler); + + ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats"); + statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/"); + statsContext.setSessionHandler(new SessionHandler()); + if (_statsPropFile != null) + { + final HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile); + Constraint constraint = new Constraint(); + constraint.setName("Admin Only"); + constraint.setRoles(new String[]{"admin"}); + constraint.setAuthenticate(true); + + ConstraintMapping cm = new ConstraintMapping(); + cm.setConstraint(constraint); + cm.setPathSpec("/*"); + + ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); + securityHandler.setLoginService(loginService); + securityHandler.setConstraintMappings(Collections.singletonList(cm)); + securityHandler.setAuthenticator(new BasicAuthenticator()); + statsContext.setSecurityHandler(securityHandler); + } + } + } + + //ensure a DefaultHandler is present + if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) + { + handlers.addHandler(new DefaultHandler()); + } + + //check a connector is configured to listen on + Connector[] connectors = _server.getConnectors(); + if (connectors == null || connectors.length == 0) + { + ServerConnector connector = new ServerConnector(_server); + connector.setPort(port); + if (host != null) + connector.setHost(host); + _server.addConnector(connector); + if (_enableStats) + connector.addBean(new ConnectionStatistics()); + } + else + { + if (_enableStats) + { + for (Connector connector : connectors) + { + ((AbstractConnector)connector).addBean(new ConnectionStatistics()); + } + } + } + + runnerServerInitialized = true; + } + + // Create a context + try (Resource ctx = Resource.newResource(args[i])) + { + if (!ctx.exists()) + usage("Context '" + ctx + "' does not exist"); + + if (contextPathSet && !(contextPath.startsWith("/"))) + contextPath = "/" + contextPath; + + // Configure the context + if (!ctx.isDirectory() && ctx.toString().toLowerCase(Locale.ENGLISH).endsWith(".xml")) + { + // It is a context config file + XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx); + xmlConfiguration.getIdMap().put("Server", _server); + ContextHandler handler = (ContextHandler)xmlConfiguration.configure(); + if (contextPathSet) + handler.setContextPath(contextPath); + _contexts.addHandler(handler); + String containerIncludeJarPattern = (String)handler.getAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN); + if (containerIncludeJarPattern == null) + containerIncludeJarPattern = CONTAINER_INCLUDE_JAR_PATTERN; + else + { + if (!containerIncludeJarPattern.contains(CONTAINER_INCLUDE_JAR_PATTERN)) + { + containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + CONTAINER_INCLUDE_JAR_PATTERN; + } + } + + handler.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern); + + //check the configurations, if not explicitly set up, then configure all of them + if (handler instanceof WebAppContext) + { + WebAppContext wac = (WebAppContext)handler; + if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0) + wac.setConfigurationClasses(PLUS_CONFIGURATION_CLASSES); + } + } + else + { + // assume it is a WAR file + WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); + webapp.setConfigurationClasses(PLUS_CONFIGURATION_CLASSES); + webapp.setAttribute(MetaInfConfiguration.CONTAINER_JAR_PATTERN, + CONTAINER_INCLUDE_JAR_PATTERN); + } + } + //reset + contextPathSet = false; + contextPath = DEFAULT_CONTEXT_PATH; + break; + } + } + + if (_server == null) + usage("No Contexts defined"); + _server.setStopAtShutdown(true); + + switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) + { + case 1: + usage("Must specify --stop-key when --stop-port is specified"); + break; + + case 2: + usage("Must specify --stop-port when --stop-key is specified"); + break; + + case 3: + ShutdownMonitor monitor = ShutdownMonitor.getInstance(); + monitor.setPort(stopPort); + monitor.setKey(stopKey); + monitor.setExitVm(true); + break; + + default: + break; + } + + if (_logFile != null) + { + CustomRequestLog requestLog = new CustomRequestLog(_logFile); + _server.setRequestLog(requestLog); + } + } + + protected void prependHandler(Handler handler, HandlerCollection handlers) + { + if (handler == null || handlers == null) + return; + + Handler[] existing = handlers.getChildHandlers(); + Handler[] children = new Handler[existing.length + 1]; + children[0] = handler; + System.arraycopy(existing, 0, children, 1, existing.length); + handlers.setHandlers(children); + } + + public void run() throws Exception + { + _server.start(); + _server.join(); + } + + private URL toURL(URI uri) + { + try + { + return uri.toURL(); + } + catch (MalformedURLException e) + { + throw new RuntimeException(e); + } + } + + /** + * Establish a classloader with custom paths (if any) + */ + protected void initClassLoader() + { + URL[] paths = Arrays.stream(_classpath.asArray()).map(this::toURL).toArray(URL[]::new); + + if (_classLoader == null && paths.length > 0) + { + ClassLoader context = Thread.currentThread().getContextClassLoader(); + + if (context == null) + { + _classLoader = new URLClassLoader(paths); + } + else + { + _classLoader = new URLClassLoader(paths, context); + } + + Thread.currentThread().setContextClassLoader(_classLoader); + } + } + + public static void main(String[] args) + { + System.err.println("WARNING: jetty-runner is deprecated."); + System.err.println(" See Jetty Documentation for startup options"); + System.err.println(" https://www.eclipse.org/jetty/documentation/"); + + Runner runner = new Runner(); + + try + { + if (args.length > 0 && args[0].equalsIgnoreCase("--help")) + { + runner.usage(null); + } + else if (args.length > 0 && args[0].equalsIgnoreCase("--version")) + { + runner.version(); + } + else + { + runner.configure(args); + runner.run(); + } + } + catch (Exception e) + { + e.printStackTrace(); + runner.usage(null); + } + } +} diff --git a/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java b/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java new file mode 100644 index 00000000000..8cf44e618e9 --- /dev/null +++ b/jetty-runner/src/main/java/org/eclipse/jetty/runner/package-info.java @@ -0,0 +1,23 @@ +// +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under +// the terms of the Eclipse Public License 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0 +// +// This Source Code may also be made available under the following +// Secondary Licenses when the conditions for such availability set +// forth in the Eclipse Public License, v. 2.0 are satisfied: +// the Apache License v2.0 which is available at +// https://www.apache.org/licenses/LICENSE-2.0 +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +/** + * Jetty Runner : Embedded Jetty Tool for running webapps directly + */ +package org.eclipse.jetty.runner; + diff --git a/jetty-runner/src/main/resources/MANIFEST.MF b/jetty-runner/src/main/resources/MANIFEST.MF new file mode 100644 index 00000000000..fa816753df9 --- /dev/null +++ b/jetty-runner/src/main/resources/MANIFEST.MF @@ -0,0 +1 @@ +Comment: Jetty Runner diff --git a/pom.xml b/pom.xml index 8e4ea9e1e34..8cc78b4e2f1 100644 --- a/pom.xml +++ b/pom.xml @@ -132,6 +132,7 @@ examples jetty-quickstart jetty-distribution + jetty-runner jetty-http-spi jetty-osgi jetty-alpn From a855744aeb7d876f41aab4028b8b2299f8b1457f Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Thu, 20 Feb 2020 10:25:57 +0100 Subject: [PATCH 25/27] release buffer in client as well Signed-off-by: Greg Wilkins --- .../java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java index 44314749ee8..398a77aee32 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpSenderOverHTTP.java @@ -230,6 +230,8 @@ public class HttpSenderOverHTTP extends HttpSender } case HEADER_OVERFLOW: { + httpClient.getByteBufferPool().release(headerBuffer); + headerBuffer = null; throw new BadMessageException(INTERNAL_SERVER_ERROR_500, "Request header too large"); } case NEED_CHUNK: From 8c7861d21060a9a5337570a785f66e36f36e3106 Mon Sep 17 00:00:00 2001 From: Greg Wilkins Date: Thu, 20 Feb 2020 10:34:07 +0100 Subject: [PATCH 26/27] fixed spelling Signed-off-by: Greg Wilkins --- .../src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index 3ca8f30b39d..f8132f7ceb6 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -435,7 +435,7 @@ public class XmlConfiguration } catch (NoSuchMethodException x) { - throw new IllegalStateException(String.format("No maatching constructor %s in %s", oClass, _configuration)); + throw new IllegalStateException(String.format("No matching constructor %s in %s", oClass, _configuration)); } } if (id != null) From d83e1c93ef3f9ec88e95503b68dea172b189387a Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Thu, 20 Feb 2020 12:23:18 +0100 Subject: [PATCH 27/27] Fixed copyright header after merge. Signed-off-by: Simone Bordet --- .../jetty/xml/XmlConfigurationTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java b/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java index 9acdae8aa04..6b5a96a3405 100644 --- a/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java +++ b/jetty-xml/src/test/java/org/eclipse/jetty/xml/XmlConfigurationTest.java @@ -1,19 +1,19 @@ // -// ======================================================================== -// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. -// ------------------------------------------------------------------------ -// All rights reserved. This program and the accompanying materials -// are made available under the terms of the Eclipse Public License v1.0 -// and Apache License v2.0 which accompanies this distribution. +// ======================================================================== +// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // -// The Eclipse Public License is available at -// http://www.eclipse.org/legal/epl-v10.html +// This program and the accompanying materials are made available under +// the terms of the Eclipse Public License 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0 // -// The Apache License v2.0 is available at -// http://www.opensource.org/licenses/apache2.0.php +// This Source Code may also be made available under the following +// Secondary Licenses when the conditions for such availability set +// forth in the Eclipse Public License, v. 2.0 are satisfied: +// the Apache License v2.0 which is available at +// https://www.apache.org/licenses/LICENSE-2.0 // -// You may elect to redistribute this code under either of these licenses. -// ======================================================================== +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== // package org.eclipse.jetty.xml;