You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by ma...@apache.org on 2023/02/09 16:44:32 UTC
[tomcat] branch 10.1.x updated: Code clean-up - no functional change
This is an automated email from the ASF dual-hosted git repository.
markt pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/10.1.x by this push:
new 2b22fb4719 Code clean-up - no functional change
2b22fb4719 is described below
commit 2b22fb4719a0a3bb1c3039c245dc1ea14b5533c8
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Thu Feb 9 14:39:58 2023 +0000
Code clean-up - no functional change
---
java/org/apache/coyote/AbstractProcessor.java | 679 ++++++++++-----------
java/org/apache/coyote/AbstractProcessorLight.java | 52 +-
java/org/apache/coyote/AbstractProtocol.java | 363 +++++------
java/org/apache/coyote/ActionCode.java | 99 ++-
java/org/apache/coyote/ActionHook.java | 17 +-
java/org/apache/coyote/Adapter.java | 53 +-
java/org/apache/coyote/AsyncContextCallback.java | 25 +-
java/org/apache/coyote/AsyncStateMachine.java | 105 ++--
java/org/apache/coyote/CloseNowException.java | 9 +-
java/org/apache/coyote/CompressionConfig.java | 46 +-
java/org/apache/coyote/Constants.java | 40 +-
java/org/apache/coyote/ContinueResponseTiming.java | 32 +-
java/org/apache/coyote/ErrorState.java | 33 +-
java/org/apache/coyote/InputBuffer.java | 21 +-
java/org/apache/coyote/OutputBuffer.java | 14 +-
java/org/apache/coyote/Processor.java | 62 +-
java/org/apache/coyote/ProtocolException.java | 3 +-
java/org/apache/coyote/ProtocolHandler.java | 74 +--
java/org/apache/coyote/Request.java | 159 ++---
java/org/apache/coyote/RequestGroupInfo.java | 29 +-
java/org/apache/coyote/RequestInfo.java | 40 +-
java/org/apache/coyote/Response.java | 113 ++--
java/org/apache/coyote/UpgradeProtocol.java | 73 +--
23 files changed, 962 insertions(+), 1179 deletions(-)
diff --git a/java/org/apache/coyote/AbstractProcessor.java b/java/org/apache/coyote/AbstractProcessor.java
index 50743ffece..ece5a6abda 100644
--- a/java/org/apache/coyote/AbstractProcessor.java
+++ b/java/org/apache/coyote/AbstractProcessor.java
@@ -41,8 +41,8 @@ import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
/**
- * Provides functionality and attributes common to all supported protocols
- * (currently HTTP and AJP) for processing a single request/response.
+ * Provides functionality and attributes common to all supported protocols (currently HTTP and AJP) for processing a
+ * single request/response.
*/
public abstract class AbstractProcessor extends AbstractProcessorLight implements ActionHook {
@@ -55,13 +55,11 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
protected final AsyncStateMachine asyncStateMachine;
private volatile long asyncTimeout = -1;
/*
- * Tracks the current async generation when a timeout is dispatched. In the
- * time it takes for a container thread to be allocated and the timeout
- * processing to start, it is possible that the application completes this
- * generation of async processing and starts a new one. If the timeout is
- * then processed against the new generation, response mix-up can occur.
- * This field is used to ensure that any timeout event processed is for the
- * current async generation. This prevents the response mix-up.
+ * Tracks the current async generation when a timeout is dispatched. In the time it takes for a container thread to
+ * be allocated and the timeout processing to start, it is possible that the application completes this generation
+ * of async processing and starts a new one. If the timeout is then processed against the new generation, response
+ * mix-up can occur. This field is used to ensure that any timeout event processed is for the current async
+ * generation. This prevents the response mix-up.
*/
private volatile long asyncTimeoutGeneration = 0;
protected final Request request;
@@ -95,10 +93,11 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Update the current error state to the new error state if the new error
- * state is more severe than the current error state.
+ * Update the current error state to the new error state if the new error state is more severe than the current
+ * error state.
+ *
* @param errorState The error status details
- * @param t The error which occurred
+ * @param t The error which occurred
*/
protected void setErrorState(ErrorState errorState, Throwable t) {
if (getLog().isDebugEnabled()) {
@@ -149,6 +148,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
* Set the socket wrapper being used.
+ *
* @param socketWrapper The socket wrapper
*/
protected void setSocketWrapper(SocketWrapperBase<?> socketWrapper) {
@@ -173,8 +173,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
* Provides a mechanism to trigger processing on a container thread.
*
- * @param runnable The task representing the processing that needs to take
- * place on a container thread
+ * @param runnable The task representing the processing that needs to take place on a container thread
*/
protected void execute(Runnable runnable) {
SocketWrapperBase<?> socketWrapper = this.socketWrapper;
@@ -266,9 +265,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
}
if (getLog().isDebugEnabled()) {
- getLog().debug("Socket: [" + socketWrapper +
- "], Status in: [" + status +
- "], State out: [" + state + "]");
+ getLog().debug("Socket: [" + socketWrapper + "], Status in: [" + status + "], State out: [" + state + "]");
}
return state;
@@ -347,9 +344,8 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Called when a host header is not present in the request (e.g. HTTP/1.0).
- * It populates the server name with appropriate information. The source is
- * expected to vary by protocol.
+ * Called when a host header is not present in the request (e.g. HTTP/1.0). It populates the server name with
+ * appropriate information. The source is expected to vary by protocol.
* <p>
* The default implementation is a NO-OP.
*/
@@ -359,9 +355,8 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Called when a host header is not present or is empty in the request (e.g.
- * HTTP/1.0). It populates the server port with appropriate information. The
- * source is expected to vary by protocol.
+ * Called when a host header is not present or is empty in the request (e.g. HTTP/1.0). It populates the server port
+ * with appropriate information. The source is expected to vary by protocol.
* <p>
* The default implementation is a NO-OP.
*/
@@ -373,283 +368,283 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
@Override
public final void action(ActionCode actionCode, Object param) {
switch (actionCode) {
- // 'Normal' servlet support
- case COMMIT: {
- if (!response.isCommitted()) {
+ // 'Normal' servlet support
+ case COMMIT: {
+ if (!response.isCommitted()) {
+ try {
+ // Validate and write response headers
+ prepareResponse();
+ } catch (IOException e) {
+ handleIOException(e);
+ }
+ }
+ break;
+ }
+ case CLOSE: {
+ action(ActionCode.COMMIT, null);
try {
- // Validate and write response headers
- prepareResponse();
+ finishResponse();
} catch (IOException e) {
handleIOException(e);
}
+ break;
}
- break;
- }
- case CLOSE: {
- action(ActionCode.COMMIT, null);
- try {
- finishResponse();
- } catch (IOException e) {
- handleIOException(e);
+ case ACK: {
+ ack((ContinueResponseTiming) param);
+ break;
}
- break;
- }
- case ACK: {
- ack((ContinueResponseTiming) param);
- break;
- }
- case CLIENT_FLUSH: {
- action(ActionCode.COMMIT, null);
- try {
- flush();
- } catch (IOException e) {
- handleIOException(e);
- response.setErrorException(e);
+ case CLIENT_FLUSH: {
+ action(ActionCode.COMMIT, null);
+ try {
+ flush();
+ } catch (IOException e) {
+ handleIOException(e);
+ response.setErrorException(e);
+ }
+ break;
+ }
+ case AVAILABLE: {
+ request.setAvailable(available(Boolean.TRUE.equals(param)));
+ break;
+ }
+ case REQ_SET_BODY_REPLAY: {
+ ByteChunk body = (ByteChunk) param;
+ setRequestBody(body);
+ break;
}
- break;
- }
- case AVAILABLE: {
- request.setAvailable(available(Boolean.TRUE.equals(param)));
- break;
- }
- case REQ_SET_BODY_REPLAY: {
- ByteChunk body = (ByteChunk) param;
- setRequestBody(body);
- break;
- }
- // Error handling
- case IS_ERROR: {
- ((AtomicBoolean) param).set(getErrorState().isError());
- break;
- }
- case IS_IO_ALLOWED: {
- ((AtomicBoolean) param).set(getErrorState().isIoAllowed());
- break;
- }
- case CLOSE_NOW: {
- // Prevent further writes to the response
- setSwallowResponse();
- if (param instanceof Throwable) {
- setErrorState(ErrorState.CLOSE_NOW, (Throwable) param);
- } else {
- setErrorState(ErrorState.CLOSE_NOW, null);
+ // Error handling
+ case IS_ERROR: {
+ ((AtomicBoolean) param).set(getErrorState().isError());
+ break;
+ }
+ case IS_IO_ALLOWED: {
+ ((AtomicBoolean) param).set(getErrorState().isIoAllowed());
+ break;
+ }
+ case CLOSE_NOW: {
+ // Prevent further writes to the response
+ setSwallowResponse();
+ if (param instanceof Throwable) {
+ setErrorState(ErrorState.CLOSE_NOW, (Throwable) param);
+ } else {
+ setErrorState(ErrorState.CLOSE_NOW, null);
+ }
+ break;
+ }
+ case DISABLE_SWALLOW_INPUT: {
+ // Cancelled upload or similar.
+ // No point reading the remainder of the request.
+ disableSwallowRequest();
+ // This is an error state. Make sure it is marked as such.
+ setErrorState(ErrorState.CLOSE_CLEAN, null);
+ break;
}
- break;
- }
- case DISABLE_SWALLOW_INPUT: {
- // Cancelled upload or similar.
- // No point reading the remainder of the request.
- disableSwallowRequest();
- // This is an error state. Make sure it is marked as such.
- setErrorState(ErrorState.CLOSE_CLEAN, null);
- break;
- }
- // Request attribute support
- case REQ_HOST_ADDR_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.remoteAddr().setString(socketWrapper.getRemoteAddr());
+ // Request attribute support
+ case REQ_HOST_ADDR_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.remoteAddr().setString(socketWrapper.getRemoteAddr());
+ }
+ break;
}
- break;
- }
- case REQ_PEER_ADDR_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.peerAddr().setString(socketWrapper.getRemoteAddr());
+ case REQ_PEER_ADDR_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.peerAddr().setString(socketWrapper.getRemoteAddr());
+ }
+ break;
}
- break;
- }
- case REQ_HOST_ATTRIBUTE: {
- populateRequestAttributeRemoteHost();
- break;
- }
- case REQ_LOCALPORT_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.setLocalPort(socketWrapper.getLocalPort());
+ case REQ_HOST_ATTRIBUTE: {
+ populateRequestAttributeRemoteHost();
+ break;
}
- break;
- }
- case REQ_LOCAL_ADDR_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.localAddr().setString(socketWrapper.getLocalAddr());
+ case REQ_LOCALPORT_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.setLocalPort(socketWrapper.getLocalPort());
+ }
+ break;
}
- break;
- }
- case REQ_LOCAL_NAME_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.localName().setString(socketWrapper.getLocalName());
+ case REQ_LOCAL_ADDR_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.localAddr().setString(socketWrapper.getLocalAddr());
+ }
+ break;
}
- break;
- }
- case REQ_REMOTEPORT_ATTRIBUTE: {
- if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
- request.setRemotePort(socketWrapper.getRemotePort());
+ case REQ_LOCAL_NAME_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.localName().setString(socketWrapper.getLocalName());
+ }
+ break;
+ }
+ case REQ_REMOTEPORT_ATTRIBUTE: {
+ if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
+ request.setRemotePort(socketWrapper.getRemotePort());
+ }
+ break;
}
- break;
- }
- // SSL request attribute support
- case REQ_SSL_ATTRIBUTE: {
- populateSslRequestAttributes();
- break;
- }
- case REQ_SSL_CERTIFICATE: {
- try {
- sslReHandShake();
- } catch (IOException ioe) {
- setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
+ // SSL request attribute support
+ case REQ_SSL_ATTRIBUTE: {
+ populateSslRequestAttributes();
+ break;
+ }
+ case REQ_SSL_CERTIFICATE: {
+ try {
+ sslReHandShake();
+ } catch (IOException ioe) {
+ setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe);
+ }
+ break;
}
- break;
- }
- // Servlet 3.0 asynchronous support
- case ASYNC_START: {
- asyncStateMachine.asyncStart((AsyncContextCallback) param);
- break;
- }
- case ASYNC_COMPLETE: {
- clearDispatches();
- if (asyncStateMachine.asyncComplete()) {
- processSocketEvent(SocketEvent.OPEN_READ, true);
+ // Servlet 3.0 asynchronous support
+ case ASYNC_START: {
+ asyncStateMachine.asyncStart((AsyncContextCallback) param);
+ break;
}
- break;
- }
- case ASYNC_DISPATCH: {
- if (asyncStateMachine.asyncDispatch()) {
- processSocketEvent(SocketEvent.OPEN_READ, true);
+ case ASYNC_COMPLETE: {
+ clearDispatches();
+ if (asyncStateMachine.asyncComplete()) {
+ processSocketEvent(SocketEvent.OPEN_READ, true);
+ }
+ break;
}
- break;
- }
- case ASYNC_DISPATCHED: {
- asyncStateMachine.asyncDispatched();
- break;
- }
- case ASYNC_ERROR: {
- asyncStateMachine.asyncError();
- break;
- }
- case ASYNC_IS_ASYNC: {
- ((AtomicBoolean) param).set(asyncStateMachine.isAsync());
- break;
- }
- case ASYNC_IS_COMPLETING: {
- ((AtomicBoolean) param).set(asyncStateMachine.isCompleting());
- break;
- }
- case ASYNC_IS_DISPATCHING: {
- ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching());
- break;
- }
- case ASYNC_IS_ERROR: {
- ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError());
- break;
- }
- case ASYNC_IS_STARTED: {
- ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted());
- break;
- }
- case ASYNC_IS_TIMINGOUT: {
- ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut());
- break;
- }
- case ASYNC_RUN: {
- asyncStateMachine.asyncRun((Runnable) param);
- break;
- }
- case ASYNC_SETTIMEOUT: {
- if (param == null) {
- return;
+ case ASYNC_DISPATCH: {
+ if (asyncStateMachine.asyncDispatch()) {
+ processSocketEvent(SocketEvent.OPEN_READ, true);
+ }
+ break;
+ }
+ case ASYNC_DISPATCHED: {
+ asyncStateMachine.asyncDispatched();
+ break;
+ }
+ case ASYNC_ERROR: {
+ asyncStateMachine.asyncError();
+ break;
+ }
+ case ASYNC_IS_ASYNC: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isAsync());
+ break;
+ }
+ case ASYNC_IS_COMPLETING: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isCompleting());
+ break;
+ }
+ case ASYNC_IS_DISPATCHING: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching());
+ break;
+ }
+ case ASYNC_IS_ERROR: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError());
+ break;
+ }
+ case ASYNC_IS_STARTED: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted());
+ break;
+ }
+ case ASYNC_IS_TIMINGOUT: {
+ ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut());
+ break;
+ }
+ case ASYNC_RUN: {
+ asyncStateMachine.asyncRun((Runnable) param);
+ break;
+ }
+ case ASYNC_SETTIMEOUT: {
+ if (param == null) {
+ return;
+ }
+ long timeout = ((Long) param).longValue();
+ setAsyncTimeout(timeout);
+ break;
+ }
+ case ASYNC_TIMEOUT: {
+ AtomicBoolean result = (AtomicBoolean) param;
+ result.set(asyncStateMachine.asyncTimeout());
+ break;
+ }
+ case ASYNC_POST_PROCESS: {
+ asyncStateMachine.asyncPostProcess();
+ break;
}
- long timeout = ((Long) param).longValue();
- setAsyncTimeout(timeout);
- break;
- }
- case ASYNC_TIMEOUT: {
- AtomicBoolean result = (AtomicBoolean) param;
- result.set(asyncStateMachine.asyncTimeout());
- break;
- }
- case ASYNC_POST_PROCESS: {
- asyncStateMachine.asyncPostProcess();
- break;
- }
- // Servlet 3.1 non-blocking I/O
- case REQUEST_BODY_FULLY_READ: {
- AtomicBoolean result = (AtomicBoolean) param;
- result.set(isRequestBodyFullyRead());
- break;
- }
- case NB_READ_INTEREST: {
- AtomicBoolean isReady = (AtomicBoolean)param;
- isReady.set(isReadyForRead());
- break;
- }
- case NB_WRITE_INTEREST: {
- AtomicBoolean isReady = (AtomicBoolean)param;
- isReady.set(isReadyForWrite());
- break;
- }
- case DISPATCH_READ: {
- addDispatch(DispatchType.NON_BLOCKING_READ);
- break;
- }
- case DISPATCH_WRITE: {
- addDispatch(DispatchType.NON_BLOCKING_WRITE);
- break;
- }
- case DISPATCH_EXECUTE: {
- executeDispatches();
- break;
- }
+ // Servlet 3.1 non-blocking I/O
+ case REQUEST_BODY_FULLY_READ: {
+ AtomicBoolean result = (AtomicBoolean) param;
+ result.set(isRequestBodyFullyRead());
+ break;
+ }
+ case NB_READ_INTEREST: {
+ AtomicBoolean isReady = (AtomicBoolean) param;
+ isReady.set(isReadyForRead());
+ break;
+ }
+ case NB_WRITE_INTEREST: {
+ AtomicBoolean isReady = (AtomicBoolean) param;
+ isReady.set(isReadyForWrite());
+ break;
+ }
+ case DISPATCH_READ: {
+ addDispatch(DispatchType.NON_BLOCKING_READ);
+ break;
+ }
+ case DISPATCH_WRITE: {
+ addDispatch(DispatchType.NON_BLOCKING_WRITE);
+ break;
+ }
+ case DISPATCH_EXECUTE: {
+ executeDispatches();
+ break;
+ }
- // Servlet 3.1 HTTP Upgrade
- case UPGRADE: {
- doHttpUpgrade((UpgradeToken) param);
- break;
- }
+ // Servlet 3.1 HTTP Upgrade
+ case UPGRADE: {
+ doHttpUpgrade((UpgradeToken) param);
+ break;
+ }
- // Servlet 4.0 Push requests
- case IS_PUSH_SUPPORTED: {
- AtomicBoolean result = (AtomicBoolean) param;
- result.set(isPushSupported());
- break;
- }
- case PUSH_REQUEST: {
- doPush((Request) param);
- break;
- }
+ // Servlet 4.0 Push requests
+ case IS_PUSH_SUPPORTED: {
+ AtomicBoolean result = (AtomicBoolean) param;
+ result.set(isPushSupported());
+ break;
+ }
+ case PUSH_REQUEST: {
+ doPush((Request) param);
+ break;
+ }
- // Servlet 4.0 Trailers
- case IS_TRAILER_FIELDS_READY: {
- AtomicBoolean result = (AtomicBoolean) param;
- result.set(isTrailerFieldsReady());
- break;
- }
- case IS_TRAILER_FIELDS_SUPPORTED: {
- AtomicBoolean result = (AtomicBoolean) param;
- result.set(isTrailerFieldsSupported());
- break;
- }
+ // Servlet 4.0 Trailers
+ case IS_TRAILER_FIELDS_READY: {
+ AtomicBoolean result = (AtomicBoolean) param;
+ result.set(isTrailerFieldsReady());
+ break;
+ }
+ case IS_TRAILER_FIELDS_SUPPORTED: {
+ AtomicBoolean result = (AtomicBoolean) param;
+ result.set(isTrailerFieldsSupported());
+ break;
+ }
- // Identifiers
- case PROTOCOL_REQUEST_ID: {
- @SuppressWarnings("unchecked")
- AtomicReference<Object> result = (AtomicReference<Object>) param;
- result.set(getProtocolRequestId());
- break;
- }
- case SERVLET_CONNECTION: {
- @SuppressWarnings("unchecked")
- AtomicReference<Object> result = (AtomicReference<Object>) param;
- result.set(getServletConnection());
- break;
- }
+ // Identifiers
+ case PROTOCOL_REQUEST_ID: {
+ @SuppressWarnings("unchecked")
+ AtomicReference<Object> result = (AtomicReference<Object>) param;
+ result.set(getProtocolRequestId());
+ break;
+ }
+ case SERVLET_CONNECTION: {
+ @SuppressWarnings("unchecked")
+ AtomicReference<Object> result = (AtomicReference<Object>) param;
+ result.set(getServletConnection());
+ break;
+ }
}
}
- private void handleIOException (IOException ioe) {
+ private void handleIOException(IOException ioe) {
if (ioe instanceof CloseNowException) {
// Close the channel but keep the connection open
setErrorState(ErrorState.CLOSE_NOW, ioe);
@@ -661,8 +656,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Perform any necessary processing for a non-blocking read before
- * dispatching to the adapter.
+ * Perform any necessary processing for a non-blocking read before dispatching to the adapter.
*/
protected void dispatchNonBlockingRead() {
asyncStateMachine.asyncOperation();
@@ -672,9 +666,8 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
* {@inheritDoc}
* <p>
- * Sub-classes of this base class represent a single request/response pair.
- * The timeout to be processed is, therefore, the Servlet asynchronous
- * processing timeout.
+ * Sub-classes of this base class represent a single request/response pair. The timeout to be processed is,
+ * therefore, the Servlet asynchronous processing timeout.
*/
@Override
public void timeoutAsync(long now) {
@@ -752,11 +745,11 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Processors that populate request attributes directly (e.g. AJP) should
- * over-ride this method and return {@code false}.
+ * Processors that populate request attributes directly (e.g. AJP) should over-ride this method and return
+ * {@code false}.
*
- * @return {@code true} if the SocketWrapper should be used to populate the
- * request attributes, otherwise {@code false}.
+ * @return {@code true} if the SocketWrapper should be used to populate the request attributes, otherwise
+ * {@code false}.
*/
protected boolean getPopulateRequestAttributesFromSocket() {
return true;
@@ -764,8 +757,8 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Populate the remote host request attribute. Processors (e.g. AJP) that
- * populate this from an alternative source should override this method.
+ * Populate the remote host request attribute. Processors (e.g. AJP) that populate this from an alternative source
+ * should override this method.
*/
protected void populateRequestAttributeRemoteHost() {
if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) {
@@ -775,10 +768,8 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Populate the TLS related request attributes from the {@link SSLSupport}
- * instance associated with this processor. Protocols that populate TLS
- * attributes from a different source (e.g. AJP) should override this
- * method.
+ * Populate the TLS related request attributes from the {@link SSLSupport} instance associated with this processor.
+ * Protocols that populate TLS attributes from a different source (e.g. AJP) should override this method.
*/
protected void populateSslRequestAttributes() {
try {
@@ -793,7 +784,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
}
sslO = sslSupport.getKeySize();
if (sslO != null) {
- request.setAttribute (SSLSupport.KEY_SIZE_KEY, sslO);
+ request.setAttribute(SSLSupport.KEY_SIZE_KEY, sslO);
}
sslO = sslSupport.getSessionId();
if (sslO != null) {
@@ -820,12 +811,11 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Processors that can perform a TLS re-handshake (e.g. HTTP/1.1) should
- * override this method and implement the re-handshake.
+ * Processors that can perform a TLS re-handshake (e.g. HTTP/1.1) should override this method and implement the
+ * re-handshake.
*
- * @throws IOException If authentication is required then there will be I/O
- * with the client and this exception will be thrown if
- * that goes wrong
+ * @throws IOException If authentication is required then there will be I/O with the client and this exception will
+ * be thrown if that goes wrong
*/
protected void sslReHandShake() throws IOException {
// NO-OP
@@ -870,22 +860,17 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
lock.lock();
try {
/*
- * This method is called when non-blocking IO is initiated by defining
- * a read and/or write listener in a non-container thread. It is called
- * once the non-container thread completes so that the first calls to
- * onWritePossible() and/or onDataAvailable() as appropriate are made by
- * the container.
+ * This method is called when non-blocking IO is initiated by defining a read and/or write listener in a
+ * non-container thread. It is called once the non-container thread completes so that the first calls to
+ * onWritePossible() and/or onDataAvailable() as appropriate are made by the container.
*
- * Processing the dispatches requires (TODO confirm applies without APR)
- * that the socket has been added to the waitingRequests queue. This may
- * not have occurred by the time that the non-container thread completes
- * triggering the call to this method. Therefore, the coded syncs on the
- * SocketWrapper as the container thread that initiated this
- * non-container thread holds a lock on the SocketWrapper. The container
- * thread will add the socket to the waitingRequests queue before
- * releasing the lock on the socketWrapper. Therefore, by obtaining the
- * lock on socketWrapper before processing the dispatches, we can be
- * sure that the socket has been added to the waitingRequests queue.
+ * Processing the dispatches requires (TODO confirm applies without APR) that the socket has been added
+ * to the waitingRequests queue. This may not have occurred by the time that the non-container thread
+ * completes triggering the call to this method. Therefore, the coded syncs on the SocketWrapper as the
+ * container thread that initiated this non-container thread holds a lock on the SocketWrapper. The
+ * container thread will add the socket to the waitingRequests queue before releasing the lock on the
+ * socketWrapper. Therefore, by obtaining the lock on socketWrapper before processing the dispatches, we
+ * can be sure that the socket has been added to the waitingRequests queue.
*/
while (dispatches != null && dispatches.hasNext()) {
DispatchType dispatchType = dispatches.next();
@@ -899,38 +884,31 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * {@inheritDoc}
- * Processors that implement HTTP upgrade must override this method and
- * provide the necessary token.
+ * {@inheritDoc} Processors that implement HTTP upgrade must override this method and provide the necessary token.
*/
@Override
public UpgradeToken getUpgradeToken() {
// Should never reach this code but in case we do...
- throw new IllegalStateException(
- sm.getString("abstractProcessor.httpupgrade.notsupported"));
+ throw new IllegalStateException(sm.getString("abstractProcessor.httpupgrade.notsupported"));
}
/**
- * Process an HTTP upgrade. Processors that support HTTP upgrade should
- * override this method and process the provided token.
+ * Process an HTTP upgrade. Processors that support HTTP upgrade should override this method and process the
+ * provided token.
*
- * @param upgradeToken Contains all the information necessary for the
- * Processor to process the upgrade
+ * @param upgradeToken Contains all the information necessary for the Processor to process the upgrade
*
- * @throws UnsupportedOperationException if the protocol does not support
- * HTTP upgrade
+ * @throws UnsupportedOperationException if the protocol does not support HTTP upgrade
*/
protected void doHttpUpgrade(UpgradeToken upgradeToken) {
// Should never happen
- throw new UnsupportedOperationException(
- sm.getString("abstractProcessor.httpupgrade.notsupported"));
+ throw new UnsupportedOperationException(sm.getString("abstractProcessor.httpupgrade.notsupported"));
}
/**
- * {@inheritDoc}
- * Processors that implement HTTP upgrade must override this method.
+ * {@inheritDoc} Processors that implement HTTP upgrade must override this method.
*/
@Override
public ByteBuffer getLeftoverInput() {
@@ -940,8 +918,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * {@inheritDoc}
- * Processors that implement HTTP upgrade must override this method.
+ * {@inheritDoc} Processors that implement HTTP upgrade must override this method.
*/
@Override
public boolean isUpgrade() {
@@ -953,8 +930,7 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
* Protocols that support push should override this method and return {@code
* true}.
*
- * @return {@code true} if push is supported by this processor, otherwise
- * {@code false}.
+ * @return {@code true} if push is supported by this processor, otherwise {@code false}.
*/
protected boolean isPushSupported() {
return false;
@@ -962,18 +938,14 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Process a push. Processors that support push should override this method
- * and process the provided token.
+ * Process a push. Processors that support push should override this method and process the provided token.
*
- * @param pushTarget Contains all the information necessary for the Processor
- * to process the push request
+ * @param pushTarget Contains all the information necessary for the Processor to process the push request
*
- * @throws UnsupportedOperationException if the protocol does not support
- * push
+ * @throws UnsupportedOperationException if the protocol does not support push
*/
protected void doPush(Request pushTarget) {
- throw new UnsupportedOperationException(
- sm.getString("abstractProcessor.pushrequest.notsupported"));
+ throw new UnsupportedOperationException(sm.getString("abstractProcessor.pushrequest.notsupported"));
}
@@ -981,11 +953,9 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Protocols that support trailer fields should override this method and
- * return {@code true}.
+ * Protocols that support trailer fields should override this method and return {@code true}.
*
- * @return {@code true} if trailer fields are supported by this processor,
- * otherwise {@code false}.
+ * @return {@code true} if trailer fields are supported by this processor, otherwise {@code false}.
*/
protected boolean isTrailerFieldsSupported() {
return false;
@@ -993,11 +963,10 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Protocols that provide per HTTP request IDs (e.g. Stream ID for HTTP/2)
- * should override this method and return the appropriate ID.
+ * Protocols that provide per HTTP request IDs (e.g. Stream ID for HTTP/2) should override this method and return
+ * the appropriate ID.
*
- * @return The ID associated with this request or the empty string if no
- * such ID is defined
+ * @return The ID associated with this request or the empty string if no such ID is defined
*/
protected Object getProtocolRequestId() {
return null;
@@ -1005,37 +974,31 @@ public abstract class AbstractProcessor extends AbstractProcessorLight implement
/**
- * Protocols must override this method and return an appropriate
- * ServletConnection instance
+ * Protocols must override this method and return an appropriate ServletConnection instance
*
- * @return the ServletConnection instance associated with the current
- * request.
- */
+ * @return the ServletConnection instance associated with the current request.
+ */
protected abstract ServletConnection getServletConnection();
/**
- * Flush any pending writes. Used during non-blocking writes to flush any
- * remaining data from a previous incomplete write.
+ * Flush any pending writes. Used during non-blocking writes to flush any remaining data from a previous incomplete
+ * write.
*
- * @return <code>true</code> if data remains to be flushed at the end of
- * method
+ * @return <code>true</code> if data remains to be flushed at the end of method
*
- * @throws IOException If an I/O error occurs while attempting to flush the
- * data
+ * @throws IOException If an I/O error occurs while attempting to flush the data
*/
- protected abstract boolean flushBufferedWrite() throws IOException ;
+ protected abstract boolean flushBufferedWrite() throws IOException;
/**
- * Perform any necessary clean-up processing if the dispatch resulted in the
- * completion of processing for the current request.
+ * Perform any necessary clean-up processing if the dispatch resulted in the completion of processing for the
+ * current request.
*
- * @return The state to return for the socket once the clean-up for the
- * current request has completed
+ * @return The state to return for the socket once the clean-up for the current request has completed
*
- * @throws IOException If an I/O error occurs while attempting to end the
- * request
+ * @throws IOException If an I/O error occurs while attempting to end the request
*/
protected abstract SocketState dispatchEndRequest() throws IOException;
diff --git a/java/org/apache/coyote/AbstractProcessorLight.java b/java/org/apache/coyote/AbstractProcessorLight.java
index 709530dfc8..21515c70d7 100644
--- a/java/org/apache/coyote/AbstractProcessorLight.java
+++ b/java/org/apache/coyote/AbstractProcessorLight.java
@@ -28,9 +28,8 @@ import org.apache.tomcat.util.net.SocketEvent;
import org.apache.tomcat.util.net.SocketWrapperBase;
/**
- * This is a light-weight abstract processor implementation that is intended as
- * a basis for all Processor implementations from the light-weight upgrade
- * processors to the HTTP/AJP processors.
+ * This is a light-weight abstract processor implementation that is intended as a basis for all Processor
+ * implementations from the light-weight upgrade processors to the HTTP/AJP processors.
*/
public abstract class AbstractProcessorLight implements Processor {
@@ -38,8 +37,7 @@ public abstract class AbstractProcessorLight implements Processor {
@Override
- public SocketState process(SocketWrapperBase<?> socketWrapper, SocketEvent status)
- throws IOException {
+ public SocketState process(SocketWrapperBase<?> socketWrapper, SocketEvent status) throws IOException {
SocketState state = SocketState.CLOSED;
Iterator<DispatchType> dispatches = null;
@@ -72,16 +70,15 @@ public abstract class AbstractProcessorLight implements Processor {
}
if (getLog().isDebugEnabled()) {
- getLog().debug("Socket: [" + socketWrapper +
- "], Status in: [" + status +
- "], State out: [" + state + "]");
+ getLog().debug(
+ "Socket: [" + socketWrapper + "], Status in: [" + status + "], State out: [" + state + "]");
}
if (isAsync()) {
state = asyncPostProcess();
if (getLog().isDebugEnabled()) {
- getLog().debug("Socket: [" + socketWrapper +
- "], State after async post processing: [" + state + "]");
+ getLog().debug(
+ "Socket: [" + socketWrapper + "], State after async post processing: [" + state + "]");
}
}
@@ -90,8 +87,7 @@ public abstract class AbstractProcessorLight implements Processor {
// dispatches to process.
dispatches = getIteratorAndClearDispatches();
}
- } while (state == SocketState.ASYNC_END ||
- dispatches != null && state != SocketState.CLOSED);
+ } while (state == SocketState.ASYNC_END || dispatches != null && state != SocketState.CLOSED);
return state;
}
@@ -150,8 +146,7 @@ public abstract class AbstractProcessorLight implements Processor {
*
* @param socketWrapper The connection to process
*
- * @throws IOException If an I/O error occurs during the processing of the
- * request
+ * @throws IOException If an I/O error occurs during the processing of the request
*/
protected void logAccess(SocketWrapperBase<?> socketWrapper) throws IOException {
// NO-OP by default
@@ -159,36 +154,29 @@ public abstract class AbstractProcessorLight implements Processor {
/**
- * Service a 'standard' HTTP request. This method is called for both new
- * requests and for requests that have partially read the HTTP request line
- * or HTTP headers. Once the headers have been fully read this method is not
- * called again until there is a new HTTP request to process. Note that the
- * request type may change during processing which may result in one or more
- * calls to {@link #dispatch(SocketEvent)}. Requests may be pipe-lined.
+ * Service a 'standard' HTTP request. This method is called for both new requests and for requests that have
+ * partially read the HTTP request line or HTTP headers. Once the headers have been fully read this method is not
+ * called again until there is a new HTTP request to process. Note that the request type may change during
+ * processing which may result in one or more calls to {@link #dispatch(SocketEvent)}. Requests may be pipe-lined.
*
* @param socketWrapper The connection to process
*
- * @return The state the caller should put the socket in when this method
- * returns
+ * @return The state the caller should put the socket in when this method returns
*
- * @throws IOException If an I/O error occurs during the processing of the
- * request
+ * @throws IOException If an I/O error occurs during the processing of the request
*/
protected abstract SocketState service(SocketWrapperBase<?> socketWrapper) throws IOException;
/**
- * Process an in-progress request that is not longer in standard HTTP mode.
- * Uses currently include Servlet 3.0 Async and HTTP upgrade connections.
- * Further uses may be added in the future. These will typically start as
- * HTTP requests.
+ * Process an in-progress request that is not longer in standard HTTP mode. Uses currently include Servlet 3.0 Async
+ * and HTTP upgrade connections. Further uses may be added in the future. These will typically start as HTTP
+ * requests.
*
* @param status The event to process
*
- * @return The state the caller should put the socket in when this method
- * returns
+ * @return The state the caller should put the socket in when this method returns
*
- * @throws IOException If an I/O error occurs during the processing of the
- * request
+ * @throws IOException If an I/O error occurs during the processing of the request
*/
protected abstract SocketState dispatch(SocketEvent status) throws IOException;
diff --git a/java/org/apache/coyote/AbstractProtocol.java b/java/org/apache/coyote/AbstractProtocol.java
index 55eb2a7b3c..a322f61554 100644
--- a/java/org/apache/coyote/AbstractProtocol.java
+++ b/java/org/apache/coyote/AbstractProtocol.java
@@ -50,8 +50,7 @@ import org.apache.tomcat.util.net.SocketEvent;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
-public abstract class AbstractProtocol<S> implements ProtocolHandler,
- MBeanRegistration {
+public abstract class AbstractProtocol<S> implements ProtocolHandler, MBeanRegistration {
/**
* The string manager for this package.
@@ -60,26 +59,23 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/**
- * Counter used to generate unique JMX names for connectors using automatic
- * port binding.
+ * Counter used to generate unique JMX names for connectors using automatic port binding.
*/
private static final AtomicInteger nameCounter = new AtomicInteger(0);
/**
- * Unique ID for this connector. Only used if the connector is configured
- * to use a random port as the port will change if stop(), start() is
- * called.
+ * Unique ID for this connector. Only used if the connector is configured to use a random port as the port will
+ * change if stop(), start() is called.
*/
private int nameIndex = 0;
/**
- * Endpoint that provides low-level network I/O - must be matched to the
- * ProtocolHandler implementation (ProtocolHandler using NIO, requires NIO
- * Endpoint etc.).
+ * Endpoint that provides low-level network I/O - must be matched to the ProtocolHandler implementation
+ * (ProtocolHandler using NIO, requires NIO Endpoint etc.).
*/
- private final AbstractEndpoint<S,?> endpoint;
+ private final AbstractEndpoint<S, ?> endpoint;
private Handler<S> handler;
@@ -93,7 +89,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
private ScheduledFuture<?> timeoutFuture = null;
private ScheduledFuture<?> monitorFuture;
- public AbstractProtocol(AbstractEndpoint<S,?> endpoint) {
+ public AbstractProtocol(AbstractEndpoint<S, ?> endpoint) {
this.endpoint = endpoint;
ConnectionHandler<S> cHandler = new ConnectionHandler<>(this);
getEndpoint().setHandler(cHandler);
@@ -106,17 +102,14 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// ----------------------------------------------- Generic property handling
/**
- * Generic property setter used by the digester. Other code should not need
- * to use this. The digester will only use this method if it can't find a
- * more specific setter. That means the property belongs to the Endpoint,
- * the ServerSocketFactory or some other lower level component. This method
- * ensures that it is visible to both.
+ * Generic property setter used by the digester. Other code should not need to use this. The digester will only use
+ * this method if it can't find a more specific setter. That means the property belongs to the Endpoint, the
+ * ServerSocketFactory or some other lower level component. This method ensures that it is visible to both.
*
* @param name The name of the property to set
* @param value The value, in string form, to set for the property
*
- * @return <code>true</code> if the property was set successfully, otherwise
- * <code>false</code>
+ * @return <code>true</code> if the property was set successfully, otherwise <code>false</code>
*/
public boolean setProperty(String name, String value) {
return endpoint.setProperty(name, value);
@@ -124,8 +117,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/**
- * Generic property getter used by the digester. Other code should not need
- * to use this.
+ * Generic property getter used by the digester. Other code should not need to use this.
*
* @param name The name of the property to get
*
@@ -142,55 +134,69 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
* Name of MBean for the Global Request Processor.
*/
protected ObjectName rgOname = null;
+
public ObjectName getGlobalRequestProcessorMBeanName() {
return rgOname;
}
/**
- * The adapter provides the link between the ProtocolHandler and the
- * connector.
+ * The adapter provides the link between the ProtocolHandler and the connector.
*/
protected Adapter adapter;
+
@Override
- public void setAdapter(Adapter adapter) { this.adapter = adapter; }
+ public void setAdapter(Adapter adapter) {
+ this.adapter = adapter;
+ }
+
@Override
- public Adapter getAdapter() { return adapter; }
+ public Adapter getAdapter() {
+ return adapter;
+ }
/**
- * The maximum number of idle processors that will be retained in the cache
- * and re-used with a subsequent request. The default is 200. A value of -1
- * means unlimited. In the unlimited case, the theoretical maximum number of
- * cached Processor objects is {@link #getMaxConnections()} although it will
- * usually be closer to {@link #getMaxThreads()}.
+ * The maximum number of idle processors that will be retained in the cache and re-used with a subsequent request.
+ * The default is 200. A value of -1 means unlimited. In the unlimited case, the theoretical maximum number of
+ * cached Processor objects is {@link #getMaxConnections()} although it will usually be closer to
+ * {@link #getMaxThreads()}.
*/
protected int processorCache = 200;
- public int getProcessorCache() { return this.processorCache; }
+
+ public int getProcessorCache() {
+ return this.processorCache;
+ }
+
public void setProcessorCache(int processorCache) {
this.processorCache = processorCache;
}
private String clientCertProvider = null;
+
/**
- * When client certificate information is presented in a form other than
- * instances of {@link java.security.cert.X509Certificate} it needs to be
- * converted before it can be used and this property controls which JSSE
- * provider is used to perform the conversion. For example it is used with
- * the AJP connectors and with the
- * {@link org.apache.catalina.valves.SSLValve}. If not specified, the
- * default provider will be used.
+ * When client certificate information is presented in a form other than instances of
+ * {@link java.security.cert.X509Certificate} it needs to be converted before it can be used and this property
+ * controls which JSSE provider is used to perform the conversion. For example it is used with the AJP connectors
+ * and with the {@link org.apache.catalina.valves.SSLValve}. If not specified, the default provider will be used.
*
* @return The name of the JSSE provider to use
*/
- public String getClientCertProvider() { return clientCertProvider; }
- public void setClientCertProvider(String s) { this.clientCertProvider = s; }
+ public String getClientCertProvider() {
+ return clientCertProvider;
+ }
+
+ public void setClientCertProvider(String s) {
+ this.clientCertProvider = s;
+ }
private int maxHeaderCount = 100;
+
public int getMaxHeaderCount() {
return maxHeaderCount;
}
+
public void setMaxHeaderCount(int maxHeaderCount) {
this.maxHeaderCount = maxHeaderCount;
}
@@ -211,7 +217,10 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// ---------------------- Properties that are passed through to the EndPoint
@Override
- public Executor getExecutor() { return endpoint.getExecutor(); }
+ public Executor getExecutor() {
+ return endpoint.getExecutor();
+ }
+
@Override
public void setExecutor(Executor executor) {
endpoint.setExecutor(executor);
@@ -219,93 +228,136 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
- public ScheduledExecutorService getUtilityExecutor() { return endpoint.getUtilityExecutor(); }
+ public ScheduledExecutorService getUtilityExecutor() {
+ return endpoint.getUtilityExecutor();
+ }
+
@Override
public void setUtilityExecutor(ScheduledExecutorService utilityExecutor) {
endpoint.setUtilityExecutor(utilityExecutor);
}
- public int getMaxThreads() { return endpoint.getMaxThreads(); }
+ public int getMaxThreads() {
+ return endpoint.getMaxThreads();
+ }
+
public void setMaxThreads(int maxThreads) {
endpoint.setMaxThreads(maxThreads);
}
- public int getMaxConnections() { return endpoint.getMaxConnections(); }
+ public int getMaxConnections() {
+ return endpoint.getMaxConnections();
+ }
+
public void setMaxConnections(int maxConnections) {
endpoint.setMaxConnections(maxConnections);
}
- public int getMinSpareThreads() { return endpoint.getMinSpareThreads(); }
+ public int getMinSpareThreads() {
+ return endpoint.getMinSpareThreads();
+ }
+
public void setMinSpareThreads(int minSpareThreads) {
endpoint.setMinSpareThreads(minSpareThreads);
}
- public int getThreadPriority() { return endpoint.getThreadPriority(); }
+ public int getThreadPriority() {
+ return endpoint.getThreadPriority();
+ }
+
public void setThreadPriority(int threadPriority) {
endpoint.setThreadPriority(threadPriority);
}
- public int getAcceptCount() { return endpoint.getAcceptCount(); }
- public void setAcceptCount(int acceptCount) { endpoint.setAcceptCount(acceptCount); }
+ public int getAcceptCount() {
+ return endpoint.getAcceptCount();
+ }
+
+ public void setAcceptCount(int acceptCount) {
+ endpoint.setAcceptCount(acceptCount);
+ }
- public boolean getTcpNoDelay() { return endpoint.getTcpNoDelay(); }
+ public boolean getTcpNoDelay() {
+ return endpoint.getTcpNoDelay();
+ }
+
public void setTcpNoDelay(boolean tcpNoDelay) {
endpoint.setTcpNoDelay(tcpNoDelay);
}
- public int getConnectionLinger() { return endpoint.getConnectionLinger(); }
+ public int getConnectionLinger() {
+ return endpoint.getConnectionLinger();
+ }
+
public void setConnectionLinger(int connectionLinger) {
endpoint.setConnectionLinger(connectionLinger);
}
/**
- * The time Tomcat will wait for a subsequent request before closing the
- * connection. The default is {@link #getConnectionTimeout()}.
+ * The time Tomcat will wait for a subsequent request before closing the connection. The default is
+ * {@link #getConnectionTimeout()}.
*
* @return The timeout in milliseconds
*/
- public int getKeepAliveTimeout() { return endpoint.getKeepAliveTimeout(); }
+ public int getKeepAliveTimeout() {
+ return endpoint.getKeepAliveTimeout();
+ }
+
public void setKeepAliveTimeout(int keepAliveTimeout) {
endpoint.setKeepAliveTimeout(keepAliveTimeout);
}
- public InetAddress getAddress() { return endpoint.getAddress(); }
+ public InetAddress getAddress() {
+ return endpoint.getAddress();
+ }
+
public void setAddress(InetAddress ia) {
endpoint.setAddress(ia);
}
- public int getPort() { return endpoint.getPort(); }
+ public int getPort() {
+ return endpoint.getPort();
+ }
+
public void setPort(int port) {
endpoint.setPort(port);
}
- public int getPortOffset() { return endpoint.getPortOffset(); }
+ public int getPortOffset() {
+ return endpoint.getPortOffset();
+ }
+
public void setPortOffset(int portOffset) {
endpoint.setPortOffset(portOffset);
}
- public int getPortWithOffset() { return endpoint.getPortWithOffset(); }
+ public int getPortWithOffset() {
+ return endpoint.getPortWithOffset();
+ }
- public int getLocalPort() { return endpoint.getLocalPort(); }
+ public int getLocalPort() {
+ return endpoint.getLocalPort();
+ }
/*
- * When Tomcat expects data from the client, this is the time Tomcat will
- * wait for that data to arrive before closing the connection.
+ * When Tomcat expects data from the client, this is the time Tomcat will wait for that data to arrive before
+ * closing the connection.
*/
public int getConnectionTimeout() {
return endpoint.getConnectionTimeout();
}
+
public void setConnectionTimeout(int timeout) {
endpoint.setConnectionTimeout(timeout);
}
@@ -317,8 +369,9 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
public void setAcceptorThreadPriority(int threadPriority) {
endpoint.setAcceptorThreadPriority(threadPriority);
}
+
public int getAcceptorThreadPriority() {
- return endpoint.getAcceptorThreadPriority();
+ return endpoint.getAcceptorThreadPriority();
}
@@ -334,11 +387,9 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/**
- * The name will be prefix-address-port if address is non-null and
- * prefix-port if the address is null.
+ * The name will be prefix-address-port if address is non-null and prefix-port if the address is null.
*
- * @return A name for this protocol instance that is appropriately quoted
- * for use in an ObjectName.
+ * @return A name for this protocol instance that is appropriately quoted for use in an ObjectName.
*/
public String getName() {
return ObjectName.quote(getNameInternal());
@@ -391,8 +442,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/*
- * Primarily for debugging and testing. Could be exposed via JMX if
- * considered useful.
+ * Primarily for debugging and testing. Could be exposed via JMX if considered useful.
*/
public int getWaitingProcessorCount() {
return waitingProcessors.size();
@@ -401,7 +451,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// ----------------------------------------------- Accessors for sub-classes
- protected AbstractEndpoint<S,?> getEndpoint() {
+ protected AbstractEndpoint<S, ?> getEndpoint() {
return endpoint;
}
@@ -418,16 +468,17 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// -------------------------------------------------------- Abstract methods
/**
- * Concrete implementations need to provide access to their logger to be
- * used by the abstract classes.
+ * Concrete implementations need to provide access to their logger to be used by the abstract classes.
+ *
* @return the logger
*/
protected abstract Log getLog();
/**
- * Obtain the prefix to be used when construction a name for this protocol
- * handler. The name will be prefix-address-port.
+ * Obtain the prefix to be used when construction a name for this protocol handler. The name will be
+ * prefix-address-port.
+ *
* @return the prefix
*/
protected abstract String getNamePrefix();
@@ -435,43 +486,42 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/**
* Obtain the name of the protocol, (Http, Ajp, etc.). Used with JMX.
+ *
* @return the protocol name
*/
protected abstract String getProtocolName();
/**
- * Find a suitable handler for the protocol negotiated
- * at the network layer.
+ * Find a suitable handler for the protocol negotiated at the network layer.
+ *
* @param name The name of the requested negotiated protocol.
- * @return The instance where {@link UpgradeProtocol#getAlpnName()} matches
- * the requested protocol
+ *
+ * @return The instance where {@link UpgradeProtocol#getAlpnName()} matches the requested protocol
*/
protected abstract UpgradeProtocol getNegotiatedProtocol(String name);
/**
- * Find a suitable handler for the protocol upgraded name specified. This
- * is used for direct connection protocol selection.
+ * Find a suitable handler for the protocol upgraded name specified. This is used for direct connection protocol
+ * selection.
+ *
* @param name The name of the requested negotiated protocol.
- * @return The instance where {@link UpgradeProtocol#getAlpnName()} matches
- * the requested protocol
+ *
+ * @return The instance where {@link UpgradeProtocol#getAlpnName()} matches the requested protocol
*/
protected abstract UpgradeProtocol getUpgradeProtocol(String name);
/**
- * Create and configure a new Processor instance for the current protocol
- * implementation.
+ * Create and configure a new Processor instance for the current protocol implementation.
*
* @return A fully configured Processor instance that is ready to use
*/
protected abstract Processor createProcessor();
- protected abstract Processor createUpgradeProcessor(
- SocketWrapperBase<?> socket,
- UpgradeToken upgradeToken);
+ protected abstract Processor createUpgradeProcessor(SocketWrapperBase<?> socket, UpgradeToken upgradeToken);
// ----------------------------------------------------- JMX related methods
@@ -489,8 +539,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
}
@Override
- public ObjectName preRegister(MBeanServer server, ObjectName name)
- throws Exception {
+ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
oname = name;
mserver = server;
domain = name.getDomain();
@@ -541,9 +590,8 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// ------------------------------------------------------- Lifecycle methods
/*
- * NOTE: There is no maintenance of state or checking for valid transitions
- * within this class. It is expected that the connector will maintain state
- * and prevent invalid state transitions.
+ * NOTE: There is no maintenance of state or checking for valid transitions within this class. It is expected that
+ * the connector will maintain state and prevent invalid state transitions.
*/
@Override
@@ -564,12 +612,11 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
if (this.domain != null) {
ObjectName rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
this.rgOname = rgOname;
- Registry.getRegistry(null, null).registerComponent(
- getHandler().getGlobal(), rgOname, null);
+ Registry.getRegistry(null, null).registerComponent(getHandler().getGlobal(), rgOname, null);
}
String endpointName = getName();
- endpoint.setName(endpointName.substring(1, endpointName.length()-1));
+ endpoint.setName(endpointName.substring(1, endpointName.length() - 1));
endpoint.setDomain(domain);
endpoint.init();
@@ -584,17 +631,15 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
}
endpoint.start();
- monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(
- () -> {
- startAsyncTimeout();
- }, 0, 60, TimeUnit.SECONDS);
+ monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(() -> {
+ startAsyncTimeout();
+ }, 0, 60, TimeUnit.SECONDS);
}
/**
- * Note: The name of this method originated with the Servlet 3.0
- * asynchronous processing but evolved over time to represent a timeout that
- * is triggered independently of the socket read/write timeouts.
+ * Note: The name of this method originated with the Servlet 3.0 asynchronous processing but evolved over time to
+ * represent a timeout that is triggered independently of the socket read/write timeouts.
*/
protected void startAsyncTimeout() {
if (timeoutFuture == null || timeoutFuture.isDone()) {
@@ -606,13 +651,12 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
getLog().error(sm.getString("abstractProtocolHandler.asyncTimeoutError"), e);
}
}
- timeoutFuture = getUtilityExecutor().scheduleAtFixedRate(
- () -> {
- long now = System.currentTimeMillis();
- for (Processor processor : waitingProcessors) {
- processor.timeoutAsync(now);
- }
- }, 1, 1, TimeUnit.SECONDS);
+ timeoutFuture = getUtilityExecutor().scheduleAtFixedRate(() -> {
+ long now = System.currentTimeMillis();
+ for (Processor processor : waitingProcessors) {
+ processor.timeoutAsync(now);
+ }
+ }, 1, 1, TimeUnit.SECONDS);
}
}
@@ -640,7 +684,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public void resume() throws Exception {
- if(getLog().isInfoEnabled()) {
+ if (getLog().isInfoEnabled()) {
getLog().info(sm.getString("abstractProtocolHandler.resume", getName()));
}
@@ -650,7 +694,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public void stop() throws Exception {
- if(getLog().isInfoEnabled()) {
+ if (getLog().isInfoEnabled()) {
getLog().info(sm.getString("abstractProtocolHandler.stop", getName()));
logPortOffset();
}
@@ -671,7 +715,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public void destroy() throws Exception {
- if(getLog().isInfoEnabled()) {
+ if (getLog().isInfoEnabled()) {
getLog().info(sm.getString("abstractProtocolHandler.destroy", getName()));
logPortOffset();
}
@@ -687,8 +731,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
try {
mserver.unregisterMBean(oname);
} catch (MBeanRegistrationException | InstanceNotFoundException e) {
- getLog().info(sm.getString("abstractProtocol.mbeanDeregistrationFailed",
- oname, mserver));
+ getLog().info(sm.getString("abstractProtocol.mbeanDeregistrationFailed", oname, mserver));
}
}
}
@@ -709,16 +752,15 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public long awaitConnectionsClose(long waitMillis) {
- getLog().info(sm.getString("abstractProtocol.closeConnectionsAwait",
- Long.valueOf(waitMillis), getName()));
+ getLog().info(sm.getString("abstractProtocol.closeConnectionsAwait", Long.valueOf(waitMillis), getName()));
return endpoint.awaitConnectionsClose(waitMillis);
}
private void logPortOffset() {
if (getPort() != getPortWithOffset()) {
- getLog().info(sm.getString("abstractProtocolHandler.portOffset", getName(),
- String.valueOf(getPort()), String.valueOf(getPortOffset())));
+ getLog().info(sm.getString("abstractProtocolHandler.portOffset", getName(), String.valueOf(getPort()),
+ String.valueOf(getPortOffset())));
}
}
@@ -758,8 +800,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public SocketState process(SocketWrapperBase<S> wrapper, SocketEvent status) {
if (getLog().isDebugEnabled()) {
- getLog().debug(sm.getString("abstractConnectionHandler.process",
- wrapper.getSocket(), status));
+ getLog().debug(sm.getString("abstractConnectionHandler.process", wrapper.getSocket(), status));
}
if (wrapper == null) {
// Nothing to do. Socket has been closed.
@@ -774,17 +815,14 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// method returns.
Processor processor = (Processor) wrapper.takeCurrentProcessor();
if (getLog().isDebugEnabled()) {
- getLog().debug(sm.getString("abstractConnectionHandler.connectionsGet",
- processor, socket));
+ getLog().debug(sm.getString("abstractConnectionHandler.connectionsGet", processor, socket));
}
// Timeouts are calculated on a dedicated thread and then
// dispatched. Because of delays in the dispatch process, the
// timeout may no longer be required. Check here and avoid
// unnecessary processing.
- if (SocketEvent.TIMEOUT == status &&
- (processor == null ||
- !processor.isAsync() && !processor.isUpgrade() ||
+ if (SocketEvent.TIMEOUT == status && (processor == null || !processor.isAsync() && !processor.isUpgrade() ||
processor.isAsync() && !processor.checkAsyncTimeoutGeneration())) {
// This is effectively a NO-OP
return SocketState.OPEN;
@@ -828,13 +866,10 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
}
return SocketState.CLOSED;
/*
- * To replace the code above once OpenSSL 1.1.0 is
- * used.
- // Failed to create processor. This is a bug.
- throw new IllegalStateException(sm.getString(
- "abstractConnectionHandler.negotiatedProcessor.fail",
- negotiatedProtocol));
- */
+ * To replace the code above once OpenSSL 1.1.0 is used. // Failed to create processor. This
+ * is a bug. throw new IllegalStateException(sm.getString(
+ * "abstractConnectionHandler.negotiatedProcessor.fail", negotiatedProtocol));
+ */
}
}
}
@@ -875,9 +910,8 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
processor = upgradeProtocol.getProcessor(wrapper, getProtocol().getAdapter());
} else {
if (getLog().isDebugEnabled()) {
- getLog().debug(sm.getString(
- "abstractConnectionHandler.negotiatedProcessor.fail",
- "h2c"));
+ getLog().debug(
+ sm.getString("abstractConnectionHandler.negotiatedProcessor.fail", "h2c"));
}
// Exit loop and trigger appropriate clean-up
state = SocketState.CLOSED;
@@ -889,8 +923,8 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
// Create the upgrade processor
processor = getProtocol().createUpgradeProcessor(wrapper, upgradeToken);
if (getLog().isDebugEnabled()) {
- getLog().debug(sm.getString("abstractConnectionHandler.upgradeCreate",
- processor, wrapper));
+ getLog().debug(
+ sm.getString("abstractConnectionHandler.upgradeCreate", processor, wrapper));
}
// Initialise the upgrade handler (which may trigger
// some IO using the new protocol which is why the lines
@@ -916,7 +950,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
}
}
}
- } while ( state == SocketState.UPGRADING);
+ } while (state == SocketState.UPGRADING);
if (state == SocketState.LONG) {
// In the middle of processing a request/response. Keep the
@@ -988,19 +1022,16 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
wrapper.setCurrentProcessor(processor);
}
return state;
- } catch(java.net.SocketException e) {
+ } catch (java.net.SocketException e) {
// SocketExceptions are normal
- getLog().debug(sm.getString(
- "abstractConnectionHandler.socketexception.debug"), e);
+ getLog().debug(sm.getString("abstractConnectionHandler.socketexception.debug"), e);
} catch (java.io.IOException e) {
// IOExceptions are normal
- getLog().debug(sm.getString(
- "abstractConnectionHandler.ioexception.debug"), e);
+ getLog().debug(sm.getString("abstractConnectionHandler.ioexception.debug"), e);
} catch (ProtocolException e) {
// Protocol exceptions normally mean the client sent invalid or
// incomplete data.
- getLog().debug(sm.getString(
- "abstractConnectionHandler.protocolexception.debug"), e);
+ getLog().debug(sm.getString("abstractConnectionHandler.protocolexception.debug"), e);
}
// Future developers: if you discover any other
// rare-but-nonfatal exceptions, catch them here, and log as
@@ -1030,22 +1061,19 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
if (!processor.isAsync()) {
// This is currently only used with HTTP
// Either:
- // - this is an upgraded connection
- // - the request line/headers have not been completely
- // read
+ // - this is an upgraded connection
+ // - the request line/headers have not been completely
+ // read
socket.registerReadInterest();
}
}
/**
- * Expected to be used by the handler once the processor is no longer
- * required. Care must be taken to ensure that this method is only
- * called once per processor, after the request processing has
- * completed.
+ * Expected to be used by the handler once the processor is no longer required. Care must be taken to ensure
+ * that this method is only called once per processor, after the request processing has completed.
*
- * @param processor Processor being released (that was associated with
- * the socket)
+ * @param processor Processor being released (that was associated with the socket)
*/
private void release(Processor processor) {
if (processor != null) {
@@ -1075,8 +1103,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
/**
- * Expected to be used by the Endpoint to release resources on socket
- * close, errors etc.
+ * Expected to be used by the Endpoint to release resources on socket close, errors etc.
*/
@Override
public void release(SocketWrapperBase<S> socketWrapper) {
@@ -1090,20 +1117,15 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
synchronized (this) {
try {
long count = registerCount.incrementAndGet();
- RequestInfo rp =
- processor.getRequest().getRequestProcessor();
+ RequestInfo rp = processor.getRequest().getRequestProcessor();
rp.setGlobalProcessor(global);
ObjectName rpName = new ObjectName(
- getProtocol().getDomain() +
- ":type=RequestProcessor,worker="
- + getProtocol().getName() +
- ",name=" + getProtocol().getProtocolName() +
- "Request" + count);
+ getProtocol().getDomain() + ":type=RequestProcessor,worker=" + getProtocol().getName() +
+ ",name=" + getProtocol().getProtocolName() + "Request" + count);
if (getLog().isDebugEnabled()) {
getLog().debug("Register [" + processor + "] as [" + rpName + "]");
}
- Registry.getRegistry(null, null).registerComponent(rp,
- rpName, null);
+ Registry.getRegistry(null, null).registerComponent(rp, rpName, null);
rp.setRpName(rpName);
} catch (Exception e) {
getLog().warn(sm.getString("abstractProtocol.processorRegisterError"), e);
@@ -1127,8 +1149,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
if (getLog().isDebugEnabled()) {
getLog().debug("Unregister [" + rpName + "]");
}
- Registry.getRegistry(null, null).unregisterComponent(
- rpName);
+ Registry.getRegistry(null, null).unregisterComponent(rpName);
rp.setRpName(null);
} catch (Exception e) {
getLog().warn(sm.getString("abstractProtocol.processorUnregisterError"), e);
@@ -1140,13 +1161,11 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
@Override
public final void pause() {
/*
- * Inform all the processors associated with current connections
- * that the endpoint is being paused. Most won't care. Those
- * processing multiplexed streams may wish to take action. For
- * example, HTTP/2 may wish to stop accepting new streams.
+ * Inform all the processors associated with current connections that the endpoint is being paused. Most
+ * won't care. Those processing multiplexed streams may wish to take action. For example, HTTP/2 may wish to
+ * stop accepting new streams.
*
- * Note that even if the endpoint is resumed, there is (currently)
- * no API to inform the Processors of this.
+ * Note that even if the endpoint is resumed, there is (currently) no API to inform the Processors of this.
*/
for (SocketWrapperBase<S> wrapper : proto.getEndpoint().getConnections()) {
Processor processor = (Processor) wrapper.getCurrentProcessor();
@@ -1171,7 +1190,7 @@ public abstract class AbstractProtocol<S> implements ProtocolHandler,
public boolean push(Processor processor) {
int cacheSize = handler.getProtocol().getProcessorCache();
boolean offer = cacheSize == -1 ? true : size.get() < cacheSize;
- //avoid over growing our cache or add after we have stopped
+ // avoid over growing our cache or add after we have stopped
boolean result = false;
if (offer) {
result = super.push(processor);
diff --git a/java/org/apache/coyote/ActionCode.java b/java/org/apache/coyote/ActionCode.java
index ff3b71347d..308d3b3eee 100644
--- a/java/org/apache/coyote/ActionCode.java
+++ b/java/org/apache/coyote/ActionCode.java
@@ -17,12 +17,12 @@
package org.apache.coyote;
/**
- * ActionCodes represent callbacks from the servlet container to the coyote
- * connector. Actions are implemented by ProtocolHandler, using the ActionHook
- * interface.
+ * ActionCodes represent callbacks from the servlet container to the coyote connector. Actions are implemented by
+ * ProtocolHandler, using the ActionHook interface.
*
* @see ProtocolHandler
* @see ActionHook
+ *
* @author Remy Maucherat
*/
public enum ActionCode {
@@ -31,37 +31,32 @@ public enum ActionCode {
COMMIT,
/**
- * A serious error occurred from which it is not possible to recover safely.
- * Further attempts to write to the response should be ignored and the
- * connection needs to be closed as soon as possible. This can also be used
- * to forcibly close a connection if an error occurs after the response has
- * been committed.
+ * A serious error occurred from which it is not possible to recover safely. Further attempts to write to the
+ * response should be ignored and the connection needs to be closed as soon as possible. This can also be used to
+ * forcibly close a connection if an error occurs after the response has been committed.
*/
CLOSE_NOW,
/**
- * A flush() operation originated by the client ( i.e. a flush() on the
- * servlet output stream or writer, called by a servlet ). Argument is the
- * Response.
+ * A flush() operation originated by the client ( i.e. a flush() on the servlet output stream or writer, called by a
+ * servlet ). Argument is the Response.
*/
CLIENT_FLUSH,
/**
- * Has the processor been placed into the error state? Note that the
- * response may not have an appropriate error code set.
+ * Has the processor been placed into the error state? Note that the response may not have an appropriate error code
+ * set.
*/
IS_ERROR,
/**
- * The processor may have been placed into an error state and some error
- * states do not permit any further I/O. Is I/O currently allowed?
+ * The processor may have been placed into an error state and some error states do not permit any further I/O. Is
+ * I/O currently allowed?
*/
IS_IO_ALLOWED,
/**
- * Hook called if swallowing request input should be disabled.
- * Example: Cancel a large file upload.
- *
+ * Hook called if swallowing request input should be disabled. Example: Cancel a large file upload.
*/
DISABLE_SWALLOW_INPUT,
@@ -81,14 +76,12 @@ public enum ActionCode {
REQ_PEER_ADDR_ATTRIBUTE,
/**
- * Callback for lazy evaluation - extract the SSL-related attributes
- * including the client certificate if present.
+ * Callback for lazy evaluation - extract the SSL-related attributes including the client certificate if present.
*/
REQ_SSL_ATTRIBUTE,
/**
- * Force a TLS re-handshake and make the resulting client certificate (if
- * any) available as a request attribute.
+ * Force a TLS re-handshake and make the resulting client certificate (if any) available as a request attribute.
*/
REQ_SSL_CERTIFICATE,
@@ -128,26 +121,22 @@ public enum ActionCode {
ASYNC_START,
/**
- * Callback for an async call to
- * {@link jakarta.servlet.AsyncContext#dispatch()}.
+ * Callback for an async call to {@link jakarta.servlet.AsyncContext#dispatch()}.
*/
ASYNC_DISPATCH,
/**
- * Callback to indicate the the actual dispatch has started and that the
- * async state needs change.
+ * Callback to indicate the the actual dispatch has started and that the async state needs change.
*/
ASYNC_DISPATCHED,
/**
- * Callback for an async call to
- * {@link jakarta.servlet.AsyncContext#start(Runnable)}.
+ * Callback for an async call to {@link jakarta.servlet.AsyncContext#start(Runnable)}.
*/
ASYNC_RUN,
/**
- * Callback for an async call to
- * {@link jakarta.servlet.AsyncContext#complete()}.
+ * Callback for an async call to {@link jakarta.servlet.AsyncContext#complete()}.
*/
ASYNC_COMPLETE,
@@ -162,8 +151,7 @@ public enum ActionCode {
ASYNC_ERROR,
/**
- * Callback for an async call to
- * {@link jakarta.servlet.AsyncContext#setTimeout(long)}
+ * Callback for an async call to {@link jakarta.servlet.AsyncContext#setTimeout(long)}
*/
ASYNC_SETTIMEOUT,
@@ -193,13 +181,13 @@ public enum ActionCode {
ASYNC_IS_TIMINGOUT,
/**
- * Callback to determine if async is in error.
- */
+ * Callback to determine if async is in error.
+ */
ASYNC_IS_ERROR,
/**
- * Callback to trigger post processing. Typically only used during error
- * handling to trigger essential processing that otherwise would be skipped.
+ * Callback to trigger post processing. Typically only used during error handling to trigger essential processing
+ * that otherwise would be skipped.
*/
ASYNC_POST_PROCESS,
@@ -209,15 +197,13 @@ public enum ActionCode {
UPGRADE,
/**
- * Indicator that Servlet is interested in being
- * notified when data is available to be read.
+ * Indicator that Servlet is interested in being notified when data is available to be read.
*/
NB_READ_INTEREST,
/**
- * Used with non-blocking writes to determine if a write is currently
- * allowed (sets passed parameter to <code>true</code>) or not (sets passed
- * parameter to <code>false</code>). If a write is not allowed then callback
+ * Used with non-blocking writes to determine if a write is currently allowed (sets passed parameter to
+ * <code>true</code>) or not (sets passed parameter to <code>false</code>). If a write is not allowed then callback
* will be triggered at some future point when write becomes possible again.
*/
NB_WRITE_INTEREST,
@@ -228,21 +214,20 @@ public enum ActionCode {
REQUEST_BODY_FULLY_READ,
/**
- * Indicates that the container needs to trigger a call to onDataAvailable()
- * for the registered non-blocking read listener.
+ * Indicates that the container needs to trigger a call to onDataAvailable() for the registered non-blocking read
+ * listener.
*/
DISPATCH_READ,
/**
- * Indicates that the container needs to trigger a call to onWritePossible()
- * for the registered non-blocking write listener.
+ * Indicates that the container needs to trigger a call to onWritePossible() for the registered non-blocking write
+ * listener.
*/
DISPATCH_WRITE,
/**
- * Execute any non-blocking dispatches that have been registered via
- * {@link #DISPATCH_READ} or {@link #DISPATCH_WRITE}. Typically required
- * when the non-blocking listeners are configured on a thread where the
+ * Execute any non-blocking dispatches that have been registered via {@link #DISPATCH_READ} or
+ * {@link #DISPATCH_WRITE}. Typically required when the non-blocking listeners are configured on a thread where the
* processing wasn't triggered by a read or write event on the socket.
*/
DISPATCH_EXECUTE,
@@ -258,29 +243,25 @@ public enum ActionCode {
PUSH_REQUEST,
/**
- * Are the request trailer fields ready to be read? Note that this returns
- * true if it is known that request trailer fields are not supported so an
- * empty collection of trailers can then be read.
+ * Are the request trailer fields ready to be read? Note that this returns true if it is known that request trailer
+ * fields are not supported so an empty collection of trailers can then be read.
*/
IS_TRAILER_FIELDS_READY,
/**
- * Are HTTP trailer fields supported for the current response? Note that
- * once an HTTP/1.1 response has been committed, it will no longer support
- * trailer fields.
+ * Are HTTP trailer fields supported for the current response? Note that once an HTTP/1.1 response has been
+ * committed, it will no longer support trailer fields.
*/
IS_TRAILER_FIELDS_SUPPORTED,
/**
- * Obtain the request identifier for this request as defined by the protocol
- * in use. Note that some protocols do not define such an identifier. E.g.
- * this will be Stream ID for HTTP/2.
+ * Obtain the request identifier for this request as defined by the protocol in use. Note that some protocols do not
+ * define such an identifier. E.g. this will be Stream ID for HTTP/2.
*/
PROTOCOL_REQUEST_ID,
/**
- * Obtain the servlet connection instance for the network connection
- * supporting the current request.
+ * Obtain the servlet connection instance for the network connection supporting the current request.
*/
SERVLET_CONNECTION
}
diff --git a/java/org/apache/coyote/ActionHook.java b/java/org/apache/coyote/ActionHook.java
index 8783048e66..3411e16674 100644
--- a/java/org/apache/coyote/ActionHook.java
+++ b/java/org/apache/coyote/ActionHook.java
@@ -18,17 +18,10 @@ package org.apache.coyote;
/**
- * Action hook. Actions represent the callback mechanism used by
- * coyote servlet containers to request operations on the coyote connectors.
- * Some standard actions are defined in ActionCode, however custom
- * actions are permitted.
- *
- * The param object can be used to pass and return information related with the
- * action.
- *
- *
- * This interface is typically implemented by ProtocolHandlers, and the param
- * is usually a Request or Response object.
+ * Action hook. Actions represent the callback mechanism used by coyote servlet containers to request operations on the
+ * coyote connectors. Some standard actions are defined in ActionCode, however custom actions are permitted. The param
+ * object can be used to pass and return information related with the action. This interface is typically implemented by
+ * ProtocolHandlers, and the param is usually a Request or Response object.
*
* @author Remy Maucherat
*/
@@ -38,7 +31,7 @@ public interface ActionHook {
* Send an action to the connector.
*
* @param actionCode Type of the action
- * @param param Action parameter
+ * @param param Action parameter
*/
public void action(ActionCode actionCode, Object param);
}
diff --git a/java/org/apache/coyote/Adapter.java b/java/org/apache/coyote/Adapter.java
index c456a0be4c..ee0f1f5b29 100644
--- a/java/org/apache/coyote/Adapter.java
+++ b/java/org/apache/coyote/Adapter.java
@@ -21,8 +21,8 @@ import org.apache.tomcat.util.net.SocketEvent;
/**
* Adapter. This represents the entry point in a coyote-based servlet container.
*
- *
* @author Remy Maucherat
+ *
* @see ProtocolHandler
*/
public interface Adapter {
@@ -33,59 +33,50 @@ public interface Adapter {
* @param req The request object
* @param res The response object
*
- * @exception Exception if an error happens during handling of
- * the request. Common errors are:
- * <ul><li>IOException if an input/output error occurs and we are
- * processing an included servlet (otherwise it is swallowed and
- * handled by the top level error handler mechanism)
- * <li>ServletException if a servlet throws an exception and
- * we are processing an included servlet (otherwise it is swallowed
- * and handled by the top level error handler mechanism)
- * </ul>
- * Tomcat should be able to handle and log any other exception ( including
- * runtime exceptions )
+ * @exception Exception if an error happens during handling of the request. Common errors are:
+ * <ul>
+ * <li>IOException if an input/output error occurs and we are processing an included
+ * servlet (otherwise it is swallowed and handled by the top level error handler mechanism)
+ * <li>ServletException if a servlet throws an exception and we are processing an included
+ * servlet (otherwise it is swallowed and handled by the top level error handler mechanism)
+ * </ul>
+ * Tomcat should be able to handle and log any other exception ( including runtime
+ * exceptions )
*/
public void service(Request req, Response res) throws Exception;
/**
- * Prepare the given request/response for processing. This method requires
- * that the request object has been populated with the information available
- * from the HTTP headers.
+ * Prepare the given request/response for processing. This method requires that the request object has been
+ * populated with the information available from the HTTP headers.
*
* @param req The request object
* @param res The response object
*
- * @return <code>true</code> if processing can continue, otherwise
- * <code>false</code> in which case an appropriate error will have
- * been set on the response
+ * @return <code>true</code> if processing can continue, otherwise <code>false</code> in which case an appropriate
+ * error will have been set on the response
*
* @throws Exception If the processing fails unexpectedly
*/
public boolean prepare(Request req, Response res) throws Exception;
- public boolean asyncDispatch(Request req,Response res, SocketEvent status)
- throws Exception;
+ public boolean asyncDispatch(Request req, Response res, SocketEvent status) throws Exception;
public void log(Request req, Response res, long time);
/**
- * Assert that request and response have been recycled. If they have not
- * then log a warning and force a recycle. This method is called as a safety
- * check when a processor is being recycled and may be returned to a pool
- * for reuse.
+ * Assert that request and response have been recycled. If they have not then log a warning and force a recycle.
+ * This method is called as a safety check when a processor is being recycled and may be returned to a pool for
+ * reuse.
*
- * @param req
- * Request
- * @param res
- * Response
+ * @param req Request
+ * @param res Response
*/
public void checkRecycled(Request req, Response res);
/**
- * Provide the name of the domain to use to register MBeans for components
- * associated with the connector.
+ * Provide the name of the domain to use to register MBeans for components associated with the connector.
*
- * @return The MBean domain name
+ * @return The MBean domain name
*/
public String getDomain();
}
diff --git a/java/org/apache/coyote/AsyncContextCallback.java b/java/org/apache/coyote/AsyncContextCallback.java
index 9f9b925725..8d359c6bd2 100644
--- a/java/org/apache/coyote/AsyncContextCallback.java
+++ b/java/org/apache/coyote/AsyncContextCallback.java
@@ -17,36 +17,31 @@
package org.apache.coyote;
/**
- * Provides a mechanism for the Coyote connectors to communicate with the
- * {@link jakarta.servlet.AsyncContext}. It is implemented in this manner so that
- * the org.apache.coyote package does not have a dependency on the
+ * Provides a mechanism for the Coyote connectors to communicate with the {@link jakarta.servlet.AsyncContext}. It is
+ * implemented in this manner so that the org.apache.coyote package does not have a dependency on the
* org.apache.catalina package.
*/
public interface AsyncContextCallback {
void fireOnComplete();
/**
- * Reports if the web application associated with this async request is
- * available.
+ * Reports if the web application associated with this async request is available.
*
- * @return {@code true} if the associated web application is available,
- * otherwise {@code false}
+ * @return {@code true} if the associated web application is available, otherwise {@code false}
*/
boolean isAvailable();
/**
- * Used to notify the Context that async processing has started.
- * Specifically, for the counting of in-progress async requests to work
- * correctly, this must be called exactly once every time the
- * {@link AsyncStateMachine} transitions from DISPATCHED to any other state.
+ * Used to notify the Context that async processing has started. Specifically, for the counting of in-progress async
+ * requests to work correctly, this must be called exactly once every time the {@link AsyncStateMachine} transitions
+ * from DISPATCHED to any other state.
*/
void incrementInProgressAsyncCount();
/**
- * Used to notify the Context that async processing has ended.
- * Specifically, for the counting of in-progress async requests to work
- * correctly, this must be called exactly once every time the
- * {@link AsyncStateMachine} transitions to DISPATCHED from any other state.
+ * Used to notify the Context that async processing has ended. Specifically, for the counting of in-progress async
+ * requests to work correctly, this must be called exactly once every time the {@link AsyncStateMachine} transitions
+ * to DISPATCHED from any other state.
*/
void decrementInProgressAsyncCount();
}
diff --git a/java/org/apache/coyote/AsyncStateMachine.java b/java/org/apache/coyote/AsyncStateMachine.java
index fb9b2b11aa..4e21cf9e10 100644
--- a/java/org/apache/coyote/AsyncStateMachine.java
+++ b/java/org/apache/coyote/AsyncStateMachine.java
@@ -132,27 +132,26 @@ class AsyncStateMachine {
private static final StringManager sm = StringManager.getManager(AsyncStateMachine.class);
private enum AsyncState {
- DISPATCHED (false, false, false, false),
- STARTING (true, true, false, false),
- STARTED (true, true, false, false),
- MUST_COMPLETE (true, true, true, false),
- COMPLETE_PENDING(true, true, false, false),
- COMPLETING (true, false, true, false),
- TIMING_OUT (true, true, false, false),
- MUST_DISPATCH (true, true, false, true),
- DISPATCH_PENDING(true, true, false, false),
- DISPATCHING (true, false, false, true),
- READ_WRITE_OP (true, true, false, false),
- MUST_ERROR (true, true, false, false),
- ERROR (true, true, false, false);
+ DISPATCHED(false, false, false, false),
+ STARTING(true, true, false, false),
+ STARTED(true, true, false, false),
+ MUST_COMPLETE(true, true, true, false),
+ COMPLETE_PENDING(true, true, false, false),
+ COMPLETING(true, false, true, false),
+ TIMING_OUT(true, true, false, false),
+ MUST_DISPATCH(true, true, false, true),
+ DISPATCH_PENDING(true, true, false, false),
+ DISPATCHING(true, false, false, true),
+ READ_WRITE_OP(true, true, false, false),
+ MUST_ERROR(true, true, false, false),
+ ERROR(true, true, false, false);
private final boolean isAsync;
private final boolean isStarted;
private final boolean isCompleting;
private final boolean isDispatching;
- private AsyncState(boolean isAsync, boolean isStarted, boolean isCompleting,
- boolean isDispatching) {
+ private AsyncState(boolean isAsync, boolean isStarted, boolean isCompleting, boolean isDispatching) {
this.isAsync = isAsync;
this.isStarted = isStarted;
this.isCompleting = isCompleting;
@@ -180,12 +179,10 @@ class AsyncStateMachine {
private volatile AsyncState state = AsyncState.DISPATCHED;
private volatile long lastAsyncStart = 0;
/*
- * Tracks the current generation of async processing for this state machine.
- * The generation is incremented every time async processing is started. The
- * primary purpose of this is to enable Tomcat to detect and prevent
- * attempts to process an event for a previous generation with the current
- * generation as processing such an event usually ends badly:
- * e.g. CVE-2018-8037.
+ * Tracks the current generation of async processing for this state machine. The generation is incremented every
+ * time async processing is started. The primary purpose of this is to enable Tomcat to detect and prevent attempts
+ * to process an event for a previous generation with the current generation as processing such an event usually
+ * ends badly: e.g. CVE-2018-8037.
*/
private final AtomicLong generation = new AtomicLong(0);
// Need this to fire listener on complete
@@ -223,11 +220,10 @@ class AsyncStateMachine {
}
/**
- * Obtain the time that this connection last transitioned to async
- * processing.
+ * Obtain the time that this connection last transitioned to async processing.
*
- * @return The time (as returned by {@link System#currentTimeMillis()}) that
- * this connection last transitioned to async
+ * @return The time (as returned by {@link System#currentTimeMillis()}) that this connection last transitioned to
+ * async
*/
long getLastAsyncStart() {
return lastAsyncStart;
@@ -247,26 +243,22 @@ class AsyncStateMachine {
this.asyncCtxt = asyncCtxt;
lastAsyncStart = System.currentTimeMillis();
} else {
- throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncStart()", state));
+ throw new IllegalStateException(sm.getString("asyncStateMachine.invalidAsyncState", "asyncStart()", state));
}
}
synchronized void asyncOperation() {
- if (state==AsyncState.STARTED) {
+ if (state == AsyncState.STARTED) {
updateState(AsyncState.READ_WRITE_OP);
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncOperation()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncOperation()", state));
}
}
/*
- * Async has been processed. Whether or not to enter a long poll depends on
- * current state. For example, as per SRV.2.3.3.3 can now process calls to
- * complete() or dispatch().
+ * Async has been processed. Whether or not to enter a long poll depends on current state. For example, as per
+ * SRV.2.3.3.3 can now process calls to complete() or dispatch().
*/
synchronized SocketState asyncPostProcess() {
if (state == AsyncState.COMPLETE_PENDING) {
@@ -277,7 +269,7 @@ class AsyncStateMachine {
clearNonBlockingListeners();
updateState(AsyncState.DISPATCHING);
return SocketState.ASYNC_END;
- } else if (state == AsyncState.STARTING || state == AsyncState.READ_WRITE_OP) {
+ } else if (state == AsyncState.STARTING || state == AsyncState.READ_WRITE_OP) {
updateState(AsyncState.STARTED);
return SocketState.LONG;
} else if (state == AsyncState.MUST_COMPLETE || state == AsyncState.COMPLETING) {
@@ -298,8 +290,7 @@ class AsyncStateMachine {
return SocketState.LONG;
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncPostProcess()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncPostProcess()", state));
}
}
@@ -327,8 +318,7 @@ class AsyncStateMachine {
// request/response associated with the AsyncContext so need a new
// container thread to process the different request/response.
triggerDispatch = true;
- } else if (state == AsyncState.READ_WRITE_OP || state == AsyncState.TIMING_OUT ||
- state == AsyncState.ERROR) {
+ } else if (state == AsyncState.READ_WRITE_OP || state == AsyncState.TIMING_OUT || state == AsyncState.ERROR) {
// Read/write operations can happen on or off a container thread but
// while in this state the call to listener that triggers the
// read/write will be in progress on a container thread.
@@ -342,8 +332,7 @@ class AsyncStateMachine {
updateState(AsyncState.COMPLETING);
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncComplete()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncComplete()", state));
}
return triggerDispatch;
}
@@ -353,16 +342,14 @@ class AsyncStateMachine {
if (state == AsyncState.STARTED) {
updateState(AsyncState.TIMING_OUT);
return true;
- } else if (state == AsyncState.COMPLETING ||
- state == AsyncState.DISPATCHING ||
+ } else if (state == AsyncState.COMPLETING || state == AsyncState.DISPATCHING ||
state == AsyncState.DISPATCHED) {
// NOOP - App called complete() or dispatch() between the the
// timeout firing and execution reaching this point
return false;
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncTimeout()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncTimeout()", state));
}
}
@@ -390,8 +377,7 @@ class AsyncStateMachine {
// request/response associated with the AsyncContext so need a new
// container thread to process the different request/response.
triggerDispatch = true;
- } else if (state == AsyncState.READ_WRITE_OP || state == AsyncState.TIMING_OUT ||
- state == AsyncState.ERROR) {
+ } else if (state == AsyncState.READ_WRITE_OP || state == AsyncState.TIMING_OUT || state == AsyncState.ERROR) {
// Read/write operations can happen on or off a container thread but
// while in this state the call to listener that triggers the
// read/write will be in progress on a container thread.
@@ -405,22 +391,19 @@ class AsyncStateMachine {
updateState(AsyncState.DISPATCHING);
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncDispatch()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatch()", state));
}
return triggerDispatch;
}
synchronized void asyncDispatched() {
- if (state == AsyncState.DISPATCHING ||
- state == AsyncState.MUST_DISPATCH) {
+ if (state == AsyncState.DISPATCHING || state == AsyncState.MUST_DISPATCH) {
updateState(AsyncState.DISPATCHED);
asyncCtxt.decrementInProgressAsyncCount();
} else {
throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncDispatched()", state));
+ sm.getString("asyncStateMachine.invalidAsyncState", "asyncDispatched()", state));
}
}
@@ -445,8 +428,7 @@ class AsyncStateMachine {
synchronized void asyncRun(Runnable runnable) {
- if (state == AsyncState.STARTING || state == AsyncState.STARTED ||
- state == AsyncState.READ_WRITE_OP) {
+ if (state == AsyncState.STARTING || state == AsyncState.STARTED || state == AsyncState.READ_WRITE_OP) {
// Execute the runnable using a container thread from the
// Connector's thread pool. Use a wrapper to prevent a memory leak
ClassLoader oldCL;
@@ -458,28 +440,23 @@ class AsyncStateMachine {
}
try {
if (Constants.IS_SECURITY_ENABLED) {
- PrivilegedAction<Void> pa = new PrivilegedSetTccl(
- this.getClass().getClassLoader());
+ PrivilegedAction<Void> pa = new PrivilegedSetTccl(this.getClass().getClassLoader());
AccessController.doPrivileged(pa);
} else {
- Thread.currentThread().setContextClassLoader(
- this.getClass().getClassLoader());
+ Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
processor.execute(runnable);
} finally {
if (Constants.IS_SECURITY_ENABLED) {
- PrivilegedAction<Void> pa = new PrivilegedSetTccl(
- oldCL);
+ PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldCL);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(oldCL);
}
}
} else {
- throw new IllegalStateException(
- sm.getString("asyncStateMachine.invalidAsyncState",
- "asyncRun()", state));
+ throw new IllegalStateException(sm.getString("asyncStateMachine.invalidAsyncState", "asyncRun()", state));
}
}
diff --git a/java/org/apache/coyote/CloseNowException.java b/java/org/apache/coyote/CloseNowException.java
index ff15125de3..a8bb0aea62 100644
--- a/java/org/apache/coyote/CloseNowException.java
+++ b/java/org/apache/coyote/CloseNowException.java
@@ -19,11 +19,10 @@ package org.apache.coyote;
import java.io.IOException;
/**
- * This exception is thrown to signal to the Tomcat internals that an error has
- * occurred that requires the connection to be closed. For multiplexed protocols
- * such as HTTP/2, this means the channel must be closed but the connection can
- * continue. For non-multiplexed protocols, the connection must be closed. It
- * corresponds to {@link ErrorState#CLOSE_NOW}.
+ * This exception is thrown to signal to the Tomcat internals that an error has occurred that requires the connection to
+ * be closed. For multiplexed protocols such as HTTP/2, this means the channel must be closed but the connection can
+ * continue. For non-multiplexed protocols, the connection must be closed. It corresponds to
+ * {@link ErrorState#CLOSE_NOW}.
*/
public class CloseNowException extends IOException {
diff --git a/java/org/apache/coyote/CompressionConfig.java b/java/org/apache/coyote/CompressionConfig.java
index 5f4d333ffc..b4bd64c3a2 100644
--- a/java/org/apache/coyote/CompressionConfig.java
+++ b/java/org/apache/coyote/CompressionConfig.java
@@ -51,9 +51,8 @@ public class CompressionConfig {
/**
* Set compression level.
*
- * @param compression One of <code>on</code>, <code>force</code>,
- * <code>off</code> or the minimum compression size in
- * bytes which implies <code>on</code>
+ * @param compression One of <code>on</code>, <code>force</code>, <code>off</code> or the minimum compression size
+ * in bytes which implies <code>on</code>
*/
public void setCompression(String compression) {
if (compression.equals("on")) {
@@ -82,12 +81,12 @@ public class CompressionConfig {
*/
public String getCompression() {
switch (compressionLevel) {
- case 0:
- return "off";
- case 1:
- return "on";
- case 2:
- return "force";
+ case 0:
+ return "off";
+ case 1:
+ return "on";
+ case 2:
+ return "force";
}
return "off";
}
@@ -99,8 +98,7 @@ public class CompressionConfig {
/**
- * Obtain the String form of the regular expression that defines the user
- * agents to not use gzip with.
+ * Obtain the String form of the regular expression that defines the user agents to not use gzip with.
*
* @return The regular expression as a String
*/
@@ -119,19 +117,17 @@ public class CompressionConfig {
/**
- * Set no compression user agent pattern. Regular expression as supported
- * by {@link Pattern}. e.g.: <code>gorilla|desesplorer|tigrus</code>.
+ * Set no compression user agent pattern. Regular expression as supported by {@link Pattern}. e.g.:
+ * <code>gorilla|desesplorer|tigrus</code>.
*
- * @param noCompressionUserAgents The regular expression for user agent
- * strings for which compression should not
- * be applied
+ * @param noCompressionUserAgents The regular expression for user agent strings for which compression should not be
+ * applied
*/
public void setNoCompressionUserAgents(String noCompressionUserAgents) {
if (noCompressionUserAgents == null || noCompressionUserAgents.length() == 0) {
this.noCompressionUserAgents = null;
} else {
- this.noCompressionUserAgents =
- Pattern.compile(noCompressionUserAgents);
+ this.noCompressionUserAgents = Pattern.compile(noCompressionUserAgents);
}
}
@@ -174,8 +170,7 @@ public class CompressionConfig {
/**
* Set Minimum size to trigger compression.
*
- * @param compressionMinSize The minimum content length required for
- * compression in bytes
+ * @param compressionMinSize The minimum content length required for compression in bytes
*/
public void setCompressionMinSize(int compressionMinSize) {
this.compressionMinSize = compressionMinSize;
@@ -183,14 +178,13 @@ public class CompressionConfig {
/**
- * Determines if compression should be enabled for the given response and if
- * it is, sets any necessary headers to mark it as such.
+ * Determines if compression should be enabled for the given response and if it is, sets any necessary headers to
+ * mark it as such.
*
* @param request The request that triggered the response
* @param response The response to consider compressing
*
- * @return {@code true} if compression was enabled for the given response,
- * otherwise {@code false}
+ * @return {@code true} if compression was enabled for the given response, otherwise {@code false}
*/
public boolean useCompression(Request request, Response response) {
// Check if compression is enabled
@@ -279,7 +273,7 @@ public class CompressionConfig {
Pattern noCompressionUserAgents = this.noCompressionUserAgents;
if (noCompressionUserAgents != null) {
MessageBytes userAgentValueMB = request.getMimeHeaders().getValue("user-agent");
- if(userAgentValueMB != null) {
+ if (userAgentValueMB != null) {
String userAgentValue = userAgentValueMB.toString();
if (noCompressionUserAgents.matcher(userAgentValue).matches()) {
return false;
@@ -303,7 +297,7 @@ public class CompressionConfig {
* Checks if any entry in the string array starts with the specified value
*
* @param sArray the StringArray
- * @param value string
+ * @param value string
*/
private static boolean startsWithStringArray(String sArray[], String value) {
if (value == null) {
diff --git a/java/org/apache/coyote/Constants.java b/java/org/apache/coyote/Constants.java
index a431968064..8b9c94e20a 100644
--- a/java/org/apache/coyote/Constants.java
+++ b/java/org/apache/coyote/Constants.java
@@ -53,54 +53,46 @@ public final class Constants {
/**
- * The request attribute that is set to the value of {@code Boolean.TRUE}
- * if connector processing this request supports use of sendfile.
+ * The request attribute that is set to the value of {@code Boolean.TRUE} if connector processing this request
+ * supports use of sendfile.
*/
public static final String SENDFILE_SUPPORTED_ATTR = "org.apache.tomcat.sendfile.support";
/**
- * The request attribute that can be used by a servlet to pass
- * to the connector the name of the file that is to be served
- * by sendfile. The value should be {@code java.lang.String}
- * that is {@code File.getCanonicalPath()} of the file to be served.
+ * The request attribute that can be used by a servlet to pass to the connector the name of the file that is to be
+ * served by sendfile. The value should be {@code java.lang.String} that is {@code File.getCanonicalPath()} of the
+ * file to be served.
*/
public static final String SENDFILE_FILENAME_ATTR = "org.apache.tomcat.sendfile.filename";
/**
- * The request attribute that can be used by a servlet to pass
- * to the connector the start offset of the part of a file
- * that is to be served by sendfile. The value should be
- * {@code java.lang.Long}. To serve complete file
- * the value should be {@code Long.valueOf(0)}.
+ * The request attribute that can be used by a servlet to pass to the connector the start offset of the part of a
+ * file that is to be served by sendfile. The value should be {@code java.lang.Long}. To serve complete file the
+ * value should be {@code Long.valueOf(0)}.
*/
public static final String SENDFILE_FILE_START_ATTR = "org.apache.tomcat.sendfile.start";
/**
- * The request attribute that can be used by a servlet to pass
- * to the connector the end offset (not including) of the part
- * of a file that is to be served by sendfile. The value should be
- * {@code java.lang.Long}. To serve complete file
- * the value should be equal to the length of the file.
+ * The request attribute that can be used by a servlet to pass to the connector the end offset (not including) of
+ * the part of a file that is to be served by sendfile. The value should be {@code java.lang.Long}. To serve
+ * complete file the value should be equal to the length of the file.
*/
public static final String SENDFILE_FILE_END_ATTR = "org.apache.tomcat.sendfile.end";
/**
- * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may
- * be set by other similar components) that identifies for the connector the
- * remote IP address claimed to be associated with this request when a
- * request is received via one or more proxies. It is typically provided via
- * the X-Forwarded-For HTTP header.
+ * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may be set by other similar components) that
+ * identifies for the connector the remote IP address claimed to be associated with this request when a request is
+ * received via one or more proxies. It is typically provided via the X-Forwarded-For HTTP header.
*/
public static final String REMOTE_ADDR_ATTRIBUTE = "org.apache.tomcat.remoteAddr";
/**
- * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may
- * be set by other similar components) that identifies for the connector the
- * connection peer IP address.
+ * The request attribute set by the RemoteIpFilter, RemoteIpValve (and may be set by other similar components) that
+ * identifies for the connector the connection peer IP address.
*/
public static final String PEER_ADDR_ATTRIBUTE = "org.apache.tomcat.peerAddr";
}
diff --git a/java/org/apache/coyote/ContinueResponseTiming.java b/java/org/apache/coyote/ContinueResponseTiming.java
index b3672fb39b..923fe41237 100644
--- a/java/org/apache/coyote/ContinueResponseTiming.java
+++ b/java/org/apache/coyote/ContinueResponseTiming.java
@@ -19,49 +19,39 @@ package org.apache.coyote;
import org.apache.tomcat.util.res.StringManager;
/**
- * Defines timing options for responding to requests that contain a
- * '100-continue' expectations.
- *
- *
+ * Defines timing options for responding to requests that contain a '100-continue' expectations.
*/
public enum ContinueResponseTiming {
/**
- * Tomcat will automatically send the 100 intermediate response before
- * sending the request to the servlet.
+ * Tomcat will automatically send the 100 intermediate response before sending the request to the servlet.
*/
IMMEDIATELY("immediately"),
/**
- * Send the 100 intermediate response only when the servlet attempts to
- * read the request's body by either:
+ * Send the 100 intermediate response only when the servlet attempts to read the request's body by either:
* <ul>
- * <li>calling read on the InputStream returned by
- * HttpServletRequest.getInputStream</li>
- * <li>calling read on the BufferedReader returned by
- * HttpServletRequest.getReader</li>
+ * <li>calling read on the InputStream returned by HttpServletRequest.getInputStream</li>
+ * <li>calling read on the BufferedReader returned by HttpServletRequest.getReader</li>
* </ul>
- * This allows the servlet to process the request headers and possibly
- * respond before reading the request body.
+ * This allows the servlet to process the request headers and possibly respond before reading the request body.
*/
ON_REQUEST_BODY_READ("onRead"),
/**
- * Internal use only. Used to indicate that the 100 intermediate response
- * should be sent if possible regardless of the current configuration.
+ * Internal use only. Used to indicate that the 100 intermediate response should be sent if possible regardless of
+ * the current configuration.
*/
ALWAYS("always");
private static final StringManager sm = StringManager.getManager(ContinueResponseTiming.class);
- public static ContinueResponseTiming fromString(String value) {
+ public static ContinueResponseTiming fromString(String value) {
/*
- * Do this for two reasons:
- * - Not all of the Enum values are intended to be used in configuration
- * - the naming convention for Enum constants and configuration values
- * - is not consistent
+ * Do this for two reasons: - Not all of the Enum values are intended to be used in configuration - the naming
+ * convention for Enum constants and configuration values - is not consistent
*/
if (IMMEDIATELY.toString().equalsIgnoreCase(value)) {
return IMMEDIATELY;
diff --git a/java/org/apache/coyote/ErrorState.java b/java/org/apache/coyote/ErrorState.java
index 7781def3a4..34836563da 100644
--- a/java/org/apache/coyote/ErrorState.java
+++ b/java/org/apache/coyote/ErrorState.java
@@ -24,28 +24,24 @@ public enum ErrorState {
NONE(false, 0, true, true),
/**
- * The current request/response is in an error state and while it is safe to
- * complete the current response it is not safe to continue to use the
- * existing connection which must be closed once the response has been
- * completed. For multiplexed protocols, the channel must be closed when the
- * current request/response completes but the connection may continue.
+ * The current request/response is in an error state and while it is safe to complete the current response it is not
+ * safe to continue to use the existing connection which must be closed once the response has been completed. For
+ * multiplexed protocols, the channel must be closed when the current request/response completes but the connection
+ * may continue.
*/
CLOSE_CLEAN(true, 1, true, true),
/**
- * The current request/response is in an error state and it is not safe to
- * continue to use them. For multiplexed protocols (such as HTTP/2) the
- * stream/channel must be closed immediately but the connection may
- * continue. For non-multiplexed protocols (AJP, HTTP/1.x) the current
- * connection must be closed.
+ * The current request/response is in an error state and it is not safe to continue to use them. For multiplexed
+ * protocols (such as HTTP/2) the stream/channel must be closed immediately but the connection may continue. For
+ * non-multiplexed protocols (AJP, HTTP/1.x) the current connection must be closed.
*/
CLOSE_NOW(true, 2, false, true),
/**
- * An error has been detected that impacts the underlying network
- * connection. It is not safe to continue using the network connection which
- * must be closed immediately. For multiplexed protocols (such as HTTP/2)
- * this impacts all multiplexed channels.
+ * An error has been detected that impacts the underlying network connection. It is not safe to continue using the
+ * network connection which must be closed immediately. For multiplexed protocols (such as HTTP/2) this impacts all
+ * multiplexed channels.
*/
CLOSE_CONNECTION_NOW(true, 3, false, false);
@@ -54,8 +50,7 @@ public enum ErrorState {
private final boolean ioAllowed;
private final boolean connectionIoAllowed;
- private ErrorState(boolean error, int severity, boolean ioAllowed,
- boolean connectionIoAllowed) {
+ private ErrorState(boolean error, int severity, boolean ioAllowed, boolean connectionIoAllowed) {
this.error = error;
this.severity = severity;
this.ioAllowed = ioAllowed;
@@ -67,13 +62,11 @@ public enum ErrorState {
}
/**
- * Compare this ErrorState with the provided ErrorState and return the most
- * severe.
+ * Compare this ErrorState with the provided ErrorState and return the most severe.
*
* @param input The error state to compare to this one
*
- * @return The most severe error state from the the provided error state and
- * this one
+ * @return The most severe error state from the the provided error state and this one
*/
public ErrorState getMostSevere(ErrorState input) {
if (input.severity > this.severity) {
diff --git a/java/org/apache/coyote/InputBuffer.java b/java/org/apache/coyote/InputBuffer.java
index e836ee4af5..b7fd824fc9 100644
--- a/java/org/apache/coyote/InputBuffer.java
+++ b/java/org/apache/coyote/InputBuffer.java
@@ -21,22 +21,18 @@ import java.io.IOException;
import org.apache.tomcat.util.net.ApplicationBufferHandler;
/**
- * This class is only for internal use in the protocol implementation. All
- * reading from Tomcat (or adapter) should be done using Request.doRead().
+ * This class is only for internal use in the protocol implementation. All reading from Tomcat (or adapter) should be
+ * done using Request.doRead().
*/
public interface InputBuffer {
/**
- * Read from the input stream into the ByteBuffer provided by the
- * ApplicationBufferHandler.
- * IMPORTANT: the current model assumes that the protocol will 'own' the
- * ByteBuffer and return a pointer to it.
+ * Read from the input stream into the ByteBuffer provided by the ApplicationBufferHandler. IMPORTANT: the current
+ * model assumes that the protocol will 'own' the ByteBuffer and return a pointer to it.
*
- * @param handler ApplicationBufferHandler that provides the buffer to read
- * data into.
+ * @param handler ApplicationBufferHandler that provides the buffer to read data into.
*
- * @return The number of bytes that have been added to the buffer or -1 for
- * end of stream
+ * @return The number of bytes that have been added to the buffer or -1 for end of stream
*
* @throws IOException If an I/O error occurs reading from the input stream
*/
@@ -44,9 +40,8 @@ public interface InputBuffer {
/**
- * Obtain an estimate of the number of bytes that can be read without
- * blocking. Typically, this will be the number of available bytes known to
- * be buffered.
+ * Obtain an estimate of the number of bytes that can be read without blocking. Typically, this will be the number
+ * of available bytes known to be buffered.
*
* @return The number of bytes that can be read without blocking
*/
diff --git a/java/org/apache/coyote/OutputBuffer.java b/java/org/apache/coyote/OutputBuffer.java
index ad945fabb5..e694bdd273 100644
--- a/java/org/apache/coyote/OutputBuffer.java
+++ b/java/org/apache/coyote/OutputBuffer.java
@@ -20,10 +20,8 @@ import java.io.IOException;
import java.nio.ByteBuffer;
/**
- * Output buffer.
- *
- * This class is used internally by the protocol implementation. All writes from
- * higher level code should happen via Response.doWrite().
+ * Output buffer. This class is used internally by the protocol implementation. All writes from higher level code should
+ * happen via Response.doWrite().
*
* @author Remy Maucherat
*/
@@ -34,8 +32,7 @@ public interface OutputBuffer {
*
* @param chunk data to write
*
- * @return The number of bytes written which may be less than available in
- * the input chunk
+ * @return The number of bytes written which may be less than available in the input chunk
*
* @throws IOException an underlying I/O error occurred
*/
@@ -43,10 +40,9 @@ public interface OutputBuffer {
/**
- * Bytes written to the underlying socket. This includes the effects of
- * chunking, compression, etc.
+ * Bytes written to the underlying socket. This includes the effects of chunking, compression, etc.
*
- * @return Bytes written for the current request
+ * @return Bytes written for the current request
*/
public long getBytesWritten();
}
diff --git a/java/org/apache/coyote/Processor.java b/java/org/apache/coyote/Processor.java
index c58431e0a0..ad41bc4880 100644
--- a/java/org/apache/coyote/Processor.java
+++ b/java/org/apache/coyote/Processor.java
@@ -30,52 +30,43 @@ import org.apache.tomcat.util.net.SocketWrapperBase;
public interface Processor {
/**
- * Process a connection. This is called whenever an event occurs (e.g. more
- * data arrives) that allows processing to continue for a connection that is
- * not currently being processed.
+ * Process a connection. This is called whenever an event occurs (e.g. more data arrives) that allows processing to
+ * continue for a connection that is not currently being processed.
*
* @param socketWrapper The connection to process
- * @param status The status of the connection that triggered this additional
- * processing
+ * @param status The status of the connection that triggered this additional processing
*
- * @return The state the caller should put the socket in when this method
- * returns
+ * @return The state the caller should put the socket in when this method returns
*
- * @throws IOException If an I/O error occurs during the processing of the
- * request
+ * @throws IOException If an I/O error occurs during the processing of the request
*/
SocketState process(SocketWrapperBase<?> socketWrapper, SocketEvent status) throws IOException;
/**
* Generate an upgrade token.
*
- * @return An upgrade token encapsulating the information required to
- * process the upgrade request
+ * @return An upgrade token encapsulating the information required to process the upgrade request
*
- * @throws IllegalStateException if this is called on a Processor that does
- * not support upgrading
+ * @throws IllegalStateException if this is called on a Processor that does not support upgrading
*/
UpgradeToken getUpgradeToken();
/**
- * @return {@code true} if the Processor is currently processing an upgrade
- * request, otherwise {@code false}
+ * @return {@code true} if the Processor is currently processing an upgrade request, otherwise {@code false}
*/
boolean isUpgrade();
+
boolean isAsync();
/**
- * Check this processor to see if the timeout has expired and process a
- * timeout if that is that case.
+ * Check this processor to see if the timeout has expired and process a timeout if that is that case.
* <p>
- * Note: The name of this method originated with the Servlet 3.0
- * asynchronous processing but evolved over time to represent a timeout that
- * is triggered independently of the socket read/write timeouts.
+ * Note: The name of this method originated with the Servlet 3.0 asynchronous processing but evolved over time to
+ * represent a timeout that is triggered independently of the socket read/write timeouts.
*
- * @param now The time (as returned by {@link System#currentTimeMillis()} to
- * use as the current time to determine whether the timeout has
- * expired. If negative, the timeout will always be treated as ifq
- * it has expired.
+ * @param now The time (as returned by {@link System#currentTimeMillis()} to use as the current time to determine
+ * whether the timeout has expired. If negative, the timeout will always be treated as ifq it has
+ * expired.
*/
void timeoutAsync(long now);
@@ -85,8 +76,7 @@ public interface Processor {
Request getRequest();
/**
- * Recycle the processor, ready for the next request which may be on the
- * same connection or a different connection.
+ * Recycle the processor, ready for the next request which may be on the same connection or a different connection.
*/
void recycle();
@@ -102,27 +92,23 @@ public interface Processor {
*
* @return leftover bytes
*
- * @throws IllegalStateException if this is called on a Processor that does
- * not support upgrading
+ * @throws IllegalStateException if this is called on a Processor that does not support upgrading
*/
ByteBuffer getLeftoverInput();
/**
- * Informs the processor that the underlying I/O layer has stopped accepting
- * new connections. This is primarily intended to enable processors that
- * use multiplexed connections to prevent further 'streams' being added to
- * an existing multiplexed connection.
+ * Informs the processor that the underlying I/O layer has stopped accepting new connections. This is primarily
+ * intended to enable processors that use multiplexed connections to prevent further 'streams' being added to an
+ * existing multiplexed connection.
*/
void pause();
/**
- * Check to see if the async generation (each cycle of async increments the
- * generation of the AsyncStateMachine) is the same as the generation when
- * the most recent async timeout was triggered. This is intended to be used
- * to avoid unnecessary processing.
+ * Check to see if the async generation (each cycle of async increments the generation of the AsyncStateMachine) is
+ * the same as the generation when the most recent async timeout was triggered. This is intended to be used to avoid
+ * unnecessary processing.
*
- * @return {@code true} If the async generation has not changed since the
- * async timeout was triggered
+ * @return {@code true} If the async generation has not changed since the async timeout was triggered
*/
boolean checkAsyncTimeoutGeneration();
}
diff --git a/java/org/apache/coyote/ProtocolException.java b/java/org/apache/coyote/ProtocolException.java
index 9047f86853..9762e07450 100644
--- a/java/org/apache/coyote/ProtocolException.java
+++ b/java/org/apache/coyote/ProtocolException.java
@@ -17,8 +17,7 @@
package org.apache.coyote;
/**
- * Used when we need to indicate failure but the (Servlet) API doesn't declare
- * any appropriate exceptions.
+ * Used when we need to indicate failure but the (Servlet) API doesn't declare any appropriate exceptions.
*/
public class ProtocolException extends RuntimeException {
diff --git a/java/org/apache/coyote/ProtocolHandler.java b/java/org/apache/coyote/ProtocolHandler.java
index 9cf2889e8a..1b38d9d843 100644
--- a/java/org/apache/coyote/ProtocolHandler.java
+++ b/java/org/apache/coyote/ProtocolHandler.java
@@ -23,20 +23,19 @@ import java.util.concurrent.ScheduledExecutorService;
import org.apache.tomcat.util.net.SSLHostConfig;
/**
- * Abstract the protocol implementation, including threading, etc.
- *
- * This is the main interface to be implemented by a coyote protocol.
- * Adapter is the main interface to be implemented by a coyote servlet
- * container.
+ * Abstract the protocol implementation, including threading, etc. This is the main interface to be implemented by a
+ * coyote protocol. Adapter is the main interface to be implemented by a coyote servlet container.
*
* @author Remy Maucherat
* @author Costin Manolache
+ *
* @see Adapter
*/
public interface ProtocolHandler {
/**
* Return the adapter associated with the protocol handler.
+ *
* @return the adapter
*/
public Adapter getAdapter();
@@ -60,6 +59,7 @@ public interface ProtocolHandler {
/**
* Set the optional executor that will be used by the connector.
+ *
* @param executor the executor
*/
public void setExecutor(Executor executor);
@@ -67,6 +67,7 @@ public interface ProtocolHandler {
/**
* Get the utility executor that should be used by the protocol handler.
+ *
* @return the executor
*/
public ScheduledExecutorService getUtilityExecutor();
@@ -74,6 +75,7 @@ public interface ProtocolHandler {
/**
* Set the utility executor that should be used by the protocol handler.
+ *
* @param utilityExecutor the executor
*/
public void setUtilityExecutor(ScheduledExecutorService utilityExecutor);
@@ -128,20 +130,17 @@ public interface ProtocolHandler {
/**
- * Close the server socket (to prevent further connections) if the server
- * socket was bound on {@link #start()} (rather than on {@link #init()}
- * but do not perform any further shutdown.
+ * Close the server socket (to prevent further connections) if the server socket was bound on {@link #start()}
+ * (rather than on {@link #init()} but do not perform any further shutdown.
*/
public void closeServerSocketGraceful();
/**
- * Wait for the client connections to the server to close gracefully. The
- * method will return when all of the client connections have closed or the
- * method has been waiting for {@code waitTimeMillis}.
+ * Wait for the client connections to the server to close gracefully. The method will return when all of the client
+ * connections have closed or the method has been waiting for {@code waitTimeMillis}.
*
- * @param waitMillis The maximum time to wait in milliseconds for the
- * client connections to close.
+ * @param waitMillis The maximum time to wait in milliseconds for the client connections to close.
*
* @return The wait time, if any remaining when the method returned
*/
@@ -151,22 +150,22 @@ public interface ProtocolHandler {
/**
* Does this ProtocolHandler support sendfile?
*
- * @return <code>true</code> if this Protocol Handler supports sendfile,
- * otherwise <code>false</code>
+ * @return <code>true</code> if this Protocol Handler supports sendfile, otherwise <code>false</code>
*/
public boolean isSendfileSupported();
/**
* Add a new SSL configuration for a virtual host.
+ *
* @param sslHostConfig the configuration
*/
public void addSslHostConfig(SSLHostConfig sslHostConfig);
/**
- * Find all configured SSL virtual host configurations which will be used
- * by SNI.
+ * Find all configured SSL virtual host configurations which will be used by SNI.
+ *
* @return the configurations
*/
public SSLHostConfig[] findSslHostConfigs();
@@ -174,6 +173,7 @@ public interface ProtocolHandler {
/**
* Add a new protocol for used by HTTP/1.1 upgrade or ALPN.
+ *
* @param upgradeProtocol the protocol
*/
public void addUpgradeProtocol(UpgradeProtocol upgradeProtocol);
@@ -181,15 +181,16 @@ public interface ProtocolHandler {
/**
* Return all configured upgrade protocols.
+ *
* @return the protocols
*/
public UpgradeProtocol[] findUpgradeProtocols();
/**
- * Some protocols, like AJP, have a packet length that
- * shouldn't be exceeded, and this can be used to adjust the buffering
- * used by the application layer.
+ * Some protocols, like AJP, have a packet length that shouldn't be exceeded, and this can be used to adjust the
+ * buffering used by the application layer.
+ *
* @return the desired buffer size, or -1 if not relevant
*/
public default int getDesiredBufferSize() {
@@ -198,9 +199,9 @@ public interface ProtocolHandler {
/**
- * The default behavior is to identify connectors uniquely with address
- * and port. However, certain connectors are not using that and need
- * some other identifier, which then can be used as a replacement.
+ * The default behavior is to identify connectors uniquely with address and port. However, certain connectors are
+ * not using that and need some other identifier, which then can be used as a replacement.
+ *
* @return the id
*/
public default String getId() {
@@ -210,24 +211,27 @@ public interface ProtocolHandler {
/**
* Create a new ProtocolHandler for the given protocol.
+ *
* @param protocol the protocol
+ *
* @return the newly instantiated protocol handler
- * @throws ClassNotFoundException Specified protocol was not found
- * @throws InstantiationException Specified protocol could not be instantiated
- * @throws IllegalAccessException Exception occurred
- * @throws IllegalArgumentException Exception occurred
+ *
+ * @throws ClassNotFoundException Specified protocol was not found
+ * @throws InstantiationException Specified protocol could not be instantiated
+ * @throws IllegalAccessException Exception occurred
+ * @throws IllegalArgumentException Exception occurred
* @throws InvocationTargetException Exception occurred
- * @throws NoSuchMethodException Exception occurred
- * @throws SecurityException Exception occurred
+ * @throws NoSuchMethodException Exception occurred
+ * @throws SecurityException Exception occurred
*/
public static ProtocolHandler create(String protocol)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException,
- IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
- if (protocol == null || "HTTP/1.1".equals(protocol)
- || org.apache.coyote.http11.Http11NioProtocol.class.getName().equals(protocol)) {
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, NoSuchMethodException, SecurityException {
+ if (protocol == null || "HTTP/1.1".equals(protocol) ||
+ org.apache.coyote.http11.Http11NioProtocol.class.getName().equals(protocol)) {
return new org.apache.coyote.http11.Http11NioProtocol();
- } else if ("AJP/1.3".equals(protocol)
- || org.apache.coyote.ajp.AjpNioProtocol.class.getName().equals(protocol)) {
+ } else if ("AJP/1.3".equals(protocol) ||
+ org.apache.coyote.ajp.AjpNioProtocol.class.getName().equals(protocol)) {
return new org.apache.coyote.ajp.AjpNioProtocol();
} else {
// Instantiate protocol handler
diff --git a/java/org/apache/coyote/Request.java b/java/org/apache/coyote/Request.java
index 0fab691cdf..8ca3b710da 100644
--- a/java/org/apache/coyote/Request.java
+++ b/java/org/apache/coyote/Request.java
@@ -39,21 +39,13 @@ import org.apache.tomcat.util.net.ApplicationBufferHandler;
import org.apache.tomcat.util.res.StringManager;
/**
- * This is a low-level, efficient representation of a server request. Most
- * fields are GC-free, expensive operations are delayed until the user code
- * needs the information.
- *
- * Processing is delegated to modules, using a hook mechanism.
- *
- * This class is not intended for user code - it is used internally by tomcat
- * for processing the request in the most efficient way. Users ( servlets ) can
- * access the information using a facade, which provides the high-level view
- * of the request.
- *
- * Tomcat defines a number of attributes:
+ * This is a low-level, efficient representation of a server request. Most fields are GC-free, expensive operations are
+ * delayed until the user code needs the information. Processing is delegated to modules, using a hook mechanism. This
+ * class is not intended for user code - it is used internally by tomcat for processing the request in the most
+ * efficient way. Users ( servlets ) can access the information using a facade, which provides the high-level view of
+ * the request. Tomcat defines a number of attributes:
* <ul>
- * <li>"org.apache.tomcat.request" - allows access to the low-level
- * request object in trusted applications
+ * <li>"org.apache.tomcat.request" - allows access to the low-level request object in trusted applications
* </ul>
*
* @author James Duncan Davidson [duncan@eng.sun.com]
@@ -73,14 +65,12 @@ public final class Request {
private static final int INITIAL_COOKIE_SIZE = 4;
/*
- * At 100,000 requests a second there are enough IDs here for ~3,000,000
- * years before it overflows (and then we have another 3,000,000 years
- * before it gets back to zero).
+ * At 100,000 requests a second there are enough IDs here for ~3,000,000 years before it overflows (and then we have
+ * another 3,000,000 years before it gets back to zero).
*
- * Local testing shows that 5, 10, 50, 500 or 1000 threads can obtain
- * 60,000,000+ IDs a second from a single AtomicLong. That is about about
- * 17ns per request. It does not appear that the introduction of this
- * counter will cause a bottleneck for request processing.
+ * Local testing shows that 5, 10, 50, 500 or 1000 threads can obtain 60,000,000+ IDs a second from a single
+ * AtomicLong. That is about about 17ns per request. It does not appear that the introduction of this counter will
+ * cause a bottleneck for request processing.
*/
private static final AtomicLong requestIdGenerator = new AtomicLong(0);
@@ -118,12 +108,12 @@ public final class Request {
private final MessageBytes localAddrMB = MessageBytes.newInstance();
private final MimeHeaders headers = new MimeHeaders();
- private final Map<String,String> trailerFields = new HashMap<>();
+ private final Map<String, String> trailerFields = new HashMap<>();
/**
* Path parameters
*/
- private final Map<String,String> pathParameters = new HashMap<>();
+ private final Map<String, String> pathParameters = new HashMap<>();
/**
* Notes.
@@ -164,18 +154,18 @@ public final class Request {
private final MessageBytes remoteUser = MessageBytes.newInstance();
private boolean remoteUserNeedsAuthorization = false;
private final MessageBytes authType = MessageBytes.newInstance();
- private final HashMap<String,Object> attributes = new HashMap<>();
+ private final HashMap<String, Object> attributes = new HashMap<>();
private Response response;
private volatile ActionHook hook;
- private long bytesRead=0;
+ private long bytesRead = 0;
// Time of the request - useful to avoid repeated calls to System.currentTime
private long startTimeNanos = -1;
private long threadId = 0;
private int available = 0;
- private final RequestInfo reqProcessorMX=new RequestInfo(this);
+ private final RequestInfo reqProcessorMX = new RequestInfo(this);
private boolean sendfile = true;
@@ -185,9 +175,8 @@ public final class Request {
private Exception errorException = null;
/*
- * State for non-blocking output is maintained here as it is the one point
- * easily reachable from the CoyoteInputStream and the CoyoteAdapter which
- * both need access to state.
+ * State for non-blocking output is maintained here as it is the one point easily reachable from the
+ * CoyoteInputStream and the CoyoteAdapter which both need access to state.
*/
volatile ReadListener listener;
// Ensures listener is only fired after a call is isReady()
@@ -203,20 +192,17 @@ public final class Request {
public void setReadListener(ReadListener listener) {
if (listener == null) {
- throw new NullPointerException(
- sm.getString("request.nullReadListener"));
+ throw new NullPointerException(sm.getString("request.nullReadListener"));
}
if (getReadListener() != null) {
- throw new IllegalStateException(
- sm.getString("request.readListenerSet"));
+ throw new IllegalStateException(sm.getString("request.readListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
- // for async
+ // for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
- throw new IllegalStateException(
- sm.getString("request.notAsync"));
+ throw new IllegalStateException(sm.getString("request.notAsync"));
}
this.listener = listener;
@@ -307,7 +293,7 @@ public final class Request {
}
- public Map<String,String> getTrailerFields() {
+ public Map<String, String> getTrailerFields() {
return trailerFields;
}
@@ -344,11 +330,9 @@ public final class Request {
}
/**
- * Get the "virtual host", derived from the Host: header associated with
- * this request.
+ * Get the "virtual host", derived from the Host: header associated with this request.
*
- * @return The buffer holding the server name, if any. Use isNull() to check
- * if there is no value set.
+ * @return The buffer holding the server name, if any. Use isNull() to check if there is no value set.
*/
public MessageBytes serverName() {
return serverNameMB;
@@ -358,8 +342,8 @@ public final class Request {
return serverPort;
}
- public void setServerPort(int serverPort ) {
- this.serverPort=serverPort;
+ public void setServerPort(int serverPort) {
+ this.serverPort = serverPort;
}
public MessageBytes remoteAddr() {
@@ -382,19 +366,19 @@ public final class Request {
return localAddrMB;
}
- public int getRemotePort(){
+ public int getRemotePort() {
return remotePort;
}
- public void setRemotePort(int port){
+ public void setRemotePort(int port) {
this.remotePort = port;
}
- public int getLocalPort(){
+ public int getLocalPort() {
return localPort;
}
- public void setLocalPort(int port){
+ public void setLocalPort(int port) {
this.localPort = port;
}
@@ -404,9 +388,8 @@ public final class Request {
/**
* Get the character encoding used for this request.
*
- * @return The value set via {@link #setCharset(Charset)} or if no
- * call has been made to that method try to obtain if from the
- * content type.
+ * @return The value set via {@link #setCharset(Charset)} or if no call has been made to that method try to obtain
+ * if from the content type.
*/
public String getCharacterEncoding() {
if (characterEncoding == null) {
@@ -420,12 +403,10 @@ public final class Request {
/**
* Get the character encoding used for this request.
*
- * @return The value set via {@link #setCharset(Charset)} or if no
- * call has been made to that method try to obtain if from the
- * content type.
+ * @return The value set via {@link #setCharset(Charset)} or if no call has been made to that method try to obtain
+ * if from the content type.
*
- * @throws UnsupportedEncodingException If the user agent has specified an
- * invalid character encoding
+ * @throws UnsupportedEncodingException If the user agent has specified an invalid character encoding
*/
public Charset getCharset() throws UnsupportedEncodingException {
if (charset == null) {
@@ -433,7 +414,7 @@ public final class Request {
if (characterEncoding != null) {
charset = B2CConverter.getCharset(characterEncoding);
}
- }
+ }
return charset;
}
@@ -460,7 +441,7 @@ public final class Request {
}
public long getContentLengthLong() {
- if( contentLength > -1 ) {
+ if (contentLength > -1) {
return contentLength;
}
@@ -493,7 +474,7 @@ public final class Request {
public void setContentType(MessageBytes mb) {
- contentTypeMB=mb;
+ contentTypeMB = mb;
}
@@ -564,15 +545,15 @@ public final class Request {
// -------------------- Other attributes --------------------
// We can use notes for most - need to discuss what is of general interest
- public void setAttribute( String name, Object o ) {
- attributes.put( name, o );
+ public void setAttribute(String name, Object o) {
+ attributes.put(name, o);
}
- public HashMap<String,Object> getAttributes() {
+ public HashMap<String, Object> getAttributes() {
return attributes;
}
- public Object getAttribute(String name ) {
+ public Object getAttribute(String name) {
return attributes.get(name);
}
@@ -635,14 +616,10 @@ public final class Request {
/**
- * Read data from the input buffer and put it into ApplicationBufferHandler.
- *
- * The buffer is owned by the protocol implementation - it will be reused on
- * the next read. The Adapter must either process the data in place or copy
- * it to a separate buffer if it needs to hold it. In most cases this is
- * done during byte->char conversions or via InputStream. Unlike
- * InputStream, this interface allows the app to process data in place,
- * without copy.
+ * Read data from the input buffer and put it into ApplicationBufferHandler. The buffer is owned by the protocol
+ * implementation - it will be reused on the next read. The Adapter must either process the data in place or copy it
+ * to a separate buffer if it needs to hold it. In most cases this is done during byte->char conversions or via
+ * InputStream. Unlike InputStream, this interface allows the app to process data in place, without copy.
*
* @param handler The destination to which to copy the data
*
@@ -657,7 +634,7 @@ public final class Request {
int n = inputBuffer.doRead(handler);
if (n > 0) {
- bytesRead+=n;
+ bytesRead += n;
}
return n;
}
@@ -666,8 +643,7 @@ public final class Request {
// -------------------- Error tracking --------------------
/**
- * Set the error Exception that occurred during the writing of the response
- * processing.
+ * Set the error Exception that occurred during the writing of the response processing.
*
* @param ex The exception that occurred
*/
@@ -723,6 +699,7 @@ public final class Request {
/**
* @param startTime time
+ *
* @deprecated This setter will be removed in Tomcat 11
*/
@Deprecated
@@ -757,21 +734,13 @@ public final class Request {
/**
- * Used to store private data. Thread data could be used instead - but
- * if you have the req, getting/setting a note is just an array access, may
- * be faster than ThreadLocal for very frequent operations.
- *
- * Example use:
- * Catalina CoyoteAdapter:
- * ADAPTER_NOTES = 1 - stores the HttpServletRequest object ( req/res)
- *
- * To avoid conflicts, note in the range 0 - 8 are reserved for the
- * servlet container ( catalina connector, etc ), and values in 9 - 16
- * for connector use.
- *
- * 17-31 range is not allocated or used.
+ * Used to store private data. Thread data could be used instead - but if you have the req, getting/setting a note
+ * is just an array access, may be faster than ThreadLocal for very frequent operations. Example use: Catalina
+ * CoyoteAdapter: ADAPTER_NOTES = 1 - stores the HttpServletRequest object ( req/res) To avoid conflicts, note in
+ * the range 0 - 8 are reserved for the servlet container ( catalina connector, etc ), and values in 9 - 16 for
+ * connector use. 17-31 range is not allocated or used.
*
- * @param pos Index to use to store the note
+ * @param pos Index to use to store the note
* @param value The value to store at that index
*/
public final void setNote(int pos, Object value) {
@@ -788,7 +757,7 @@ public final class Request {
public void recycle() {
- bytesRead=0;
+ bytesRead = 0;
contentLength = -1;
contentTypeMB = null;
@@ -798,7 +767,7 @@ public final class Request {
headers.recycle();
trailerFields.clear();
serverNameMB.recycle();
- serverPort=-1;
+ serverPort = -1;
localAddrMB.recycle();
localNameMB.recycle();
localPort = -1;
@@ -847,7 +816,7 @@ public final class Request {
threadId = 0;
}
- // -------------------- Info --------------------
+ // -------------------- Info --------------------
public void updateCounters() {
reqProcessorMX.updateCounters();
}
@@ -861,13 +830,12 @@ public final class Request {
}
public boolean isProcessing() {
- return reqProcessorMX.getStage()==org.apache.coyote.Constants.STAGE_SERVICE;
+ return reqProcessorMX.getStage() == org.apache.coyote.Constants.STAGE_SERVICE;
}
/**
- * Parse the character encoding from the specified content type header.
- * If the content type is null, or there is no explicit character encoding,
- * <code>null</code> is returned.
+ * Parse the character encoding from the specified content type header. If the content type is null, or there is no
+ * explicit character encoding, <code>null</code> is returned.
*
* @param contentType a content type header
*/
@@ -886,8 +854,7 @@ public final class Request {
encoding = encoding.substring(0, end);
}
encoding = encoding.trim();
- if ((encoding.length() > 2) && (encoding.startsWith("\""))
- && (encoding.endsWith("\""))) {
+ if ((encoding.length() > 2) && (encoding.startsWith("\"")) && (encoding.endsWith("\""))) {
encoding = encoding.substring(1, encoding.length() - 1);
}
diff --git a/java/org/apache/coyote/RequestGroupInfo.java b/java/org/apache/coyote/RequestGroupInfo.java
index 7c6abb4eb8..843ad0d567 100644
--- a/java/org/apache/coyote/RequestGroupInfo.java
+++ b/java/org/apache/coyote/RequestGroupInfo.java
@@ -22,8 +22,7 @@ import java.util.List;
import org.apache.tomcat.util.modeler.BaseModelMBean;
/**
- * Only as a JMX artifact, to aggregate the data collected from each
- * RequestProcessor thread.
+ * Only as a JMX artifact, to aggregate the data collected from each RequestProcessor thread.
*/
public class RequestGroupInfo extends BaseModelMBean {
private final List<RequestInfo> processors = new ArrayList<>();
@@ -34,13 +33,13 @@ public class RequestGroupInfo extends BaseModelMBean {
private long deadBytesReceived = 0;
private long deadBytesSent = 0;
- public synchronized void addRequestProcessor( RequestInfo rp ) {
- processors.add( rp );
+ public synchronized void addRequestProcessor(RequestInfo rp) {
+ processors.add(rp);
}
- public synchronized void removeRequestProcessor( RequestInfo rp ) {
- if( rp != null ) {
- if( deadMaxTime < rp.getMaxTime() ) {
+ public synchronized void removeRequestProcessor(RequestInfo rp) {
+ if (rp != null) {
+ if (deadMaxTime < rp.getMaxTime()) {
deadMaxTime = rp.getMaxTime();
}
deadProcessingTime += rp.getProcessingTime();
@@ -49,7 +48,7 @@ public class RequestGroupInfo extends BaseModelMBean {
deadBytesReceived += rp.getBytesReceived();
deadBytesSent += rp.getBytesSent();
- processors.remove( rp );
+ processors.remove(rp);
}
}
@@ -57,7 +56,7 @@ public class RequestGroupInfo extends BaseModelMBean {
long maxTime = deadMaxTime;
for (RequestInfo rp : processors) {
if (maxTime < rp.getMaxTime()) {
- maxTime=rp.getMaxTime();
+ maxTime = rp.getMaxTime();
}
}
return maxTime;
@@ -82,7 +81,7 @@ public class RequestGroupInfo extends BaseModelMBean {
public synchronized void setProcessingTime(long totalTime) {
deadProcessingTime = totalTime;
for (RequestInfo rp : processors) {
- rp.setProcessingTime( totalTime );
+ rp.setProcessingTime(totalTime);
}
}
@@ -97,7 +96,7 @@ public class RequestGroupInfo extends BaseModelMBean {
public synchronized void setRequestCount(int requestCount) {
deadRequestCount = requestCount;
for (RequestInfo rp : processors) {
- rp.setRequestCount( requestCount );
+ rp.setRequestCount(requestCount);
}
}
@@ -112,7 +111,7 @@ public class RequestGroupInfo extends BaseModelMBean {
public synchronized void setErrorCount(int errorCount) {
deadErrorCount = errorCount;
for (RequestInfo rp : processors) {
- rp.setErrorCount( errorCount);
+ rp.setErrorCount(errorCount);
}
}
@@ -127,12 +126,12 @@ public class RequestGroupInfo extends BaseModelMBean {
public synchronized void setBytesReceived(long bytesReceived) {
deadBytesReceived = bytesReceived;
for (RequestInfo rp : processors) {
- rp.setBytesReceived( bytesReceived );
+ rp.setBytesReceived(bytesReceived);
}
}
public synchronized long getBytesSent() {
- long bytes=deadBytesSent;
+ long bytes = deadBytesSent;
for (RequestInfo rp : processors) {
bytes += rp.getBytesSent();
}
@@ -142,7 +141,7 @@ public class RequestGroupInfo extends BaseModelMBean {
public synchronized void setBytesSent(long bytesSent) {
deadBytesSent = bytesSent;
for (RequestInfo rp : processors) {
- rp.setBytesSent( bytesSent );
+ rp.setBytesSent(bytesSent);
}
}
diff --git a/java/org/apache/coyote/RequestInfo.java b/java/org/apache/coyote/RequestInfo.java
index 0efb30ffb1..750294062a 100644
--- a/java/org/apache/coyote/RequestInfo.java
+++ b/java/org/apache/coyote/RequestInfo.java
@@ -22,24 +22,20 @@ import javax.management.ObjectName;
/**
- * Structure holding the Request and Response objects. It also holds statistical
- * information about request processing and provide management information
- * about the requests being processed.
- *
- * Each thread uses a Request/Response pair that is recycled on each request.
- * This object provides a place to collect global low-level statistics - without
- * having to deal with synchronization ( since each thread will have it's own
- * RequestProcessorMX ).
+ * Structure holding the Request and Response objects. It also holds statistical information about request processing
+ * and provide management information about the requests being processed. Each thread uses a Request/Response pair that
+ * is recycled on each request. This object provides a place to collect global low-level statistics - without having to
+ * deal with synchronization ( since each thread will have it's own RequestProcessorMX ).
*
* @author Costin Manolache
*/
-public class RequestInfo {
- private RequestGroupInfo global=null;
+public class RequestInfo {
+ private RequestGroupInfo global = null;
// ----------------------------------------------------------- Constructors
- public RequestInfo( Request req) {
- this.req=req;
+ public RequestInfo(Request req) {
+ this.req = req;
}
public RequestGroupInfo getGlobalProcessor() {
@@ -47,12 +43,12 @@ public class RequestInfo {
}
public void setGlobalProcessor(RequestGroupInfo global) {
- if( global != null) {
- this.global=global;
- global.addRequestProcessor( this );
+ if (global != null) {
+ this.global = global;
+ global.addRequestProcessor(this);
} else {
if (this.global != null) {
- this.global.removeRequestProcessor( this );
+ this.global.removeRequestProcessor(this);
this.global = null;
}
}
@@ -65,7 +61,7 @@ public class RequestInfo {
private String workerThreadName;
private ObjectName rpName;
- // -------------------- Information about the current request -----------
+ // -------------------- Information about the current request -----------
// This is useful for long-running requests only
public String getMethod() {
@@ -103,8 +99,7 @@ public class RequestInfo {
}
/**
- * Obtain the remote address for this connection as reported by an
- * intermediate proxy (if any).
+ * Obtain the remote address for this connection as reported by an intermediate proxy (if any).
*
* @return The remote address for the this connection
*/
@@ -139,7 +134,7 @@ public class RequestInfo {
}
}
- // -------------------- Statistical data --------------------
+ // -------------------- Statistical data --------------------
// Collected at the end of each request.
private long bytesSent;
private long bytesReceived;
@@ -155,13 +150,12 @@ public class RequestInfo {
// number of response codes >= 400
private int errorCount;
- //the time of the last request
+ // the time of the last request
private long lastRequestProcessingTime = 0;
/**
- * Called by the processor before recycling the request. It'll collect
- * statistic information.
+ * Called by the processor before recycling the request. It'll collect statistic information.
*/
void updateCounters() {
bytesReceived += req.getBytesRead();
diff --git a/java/org/apache/coyote/Response.java b/java/org/apache/coyote/Response.java
index ad25baec9e..8d48119fb6 100644
--- a/java/org/apache/coyote/Response.java
+++ b/java/org/apache/coyote/Response.java
@@ -82,7 +82,7 @@ public final class Response {
final MimeHeaders headers = new MimeHeaders();
- private Supplier<Map<String,String>> trailerFieldsSupplier = null;
+ private Supplier<Map<String, String>> trailerFieldsSupplier = null;
/**
* Associated output buffer.
@@ -131,12 +131,10 @@ public final class Response {
private Exception errorException = null;
/**
- * With the introduction of async processing and the possibility of
- * non-container threads calling sendError() tracking the current error
- * state and ensuring that the correct error page is called becomes more
- * complicated. This state attribute helps by tracking the current error
- * state and informing callers that attempt to change state if the change
- * was successful or if another thread got there first.
+ * With the introduction of async processing and the possibility of non-container threads calling sendError()
+ * tracking the current error state and ensuring that the correct error page is called becomes more complicated.
+ * This state attribute helps by tracking the current error state and informing callers that attempt to change state
+ * if the change was successful or if another thread got there first.
*
* <pre>
* The state machine is very simple:
@@ -170,8 +168,8 @@ public final class Response {
return req;
}
- public void setRequest( Request req ) {
- this.req=req;
+ public void setRequest(Request req) {
+ this.req = req;
}
@@ -285,8 +283,7 @@ public final class Response {
// -----------------Error State --------------------
/**
- * Set the error Exception that occurred during the writing of the response
- * processing.
+ * Set the error Exception that occurred during the writing of the response processing.
*
* @param ex The exception that occurred
*/
@@ -354,10 +351,8 @@ public final class Response {
// -------------------- Headers --------------------
/**
- * Does the response contain the given header.
- * <br>
- * Warning: This method always returns <code>false</code> for Content-Type
- * and Content-Length.
+ * Does the response contain the given header. <br>
+ * Warning: This method always returns <code>false</code> for Content-Type and Content-Length.
*
* @param name The name of the header of interest
*
@@ -369,13 +364,13 @@ public final class Response {
public void setHeader(String name, String value) {
- char cc=name.charAt(0);
- if( cc=='C' || cc=='c' ) {
- if( checkSpecialHeader(name, value) ) {
+ char cc = name.charAt(0);
+ if (cc == 'C' || cc == 'c') {
+ if (checkSpecialHeader(name, value)) {
return;
}
}
- headers.setValue(name).setString( value);
+ headers.setValue(name).setString(value);
}
@@ -385,9 +380,9 @@ public final class Response {
public void addHeader(String name, String value, Charset charset) {
- char cc=name.charAt(0);
- if( cc=='C' || cc=='c' ) {
- if( checkSpecialHeader(name, value) ) {
+ char cc = name.charAt(0);
+ if (cc == 'C' || cc == 'c') {
+ if (checkSpecialHeader(name, value)) {
return;
}
}
@@ -416,23 +411,22 @@ public final class Response {
/**
- * Set internal fields for special header names.
- * Called from set/addHeader.
- * Return true if the header is special, no need to set the header.
+ * Set internal fields for special header names. Called from set/addHeader. Return true if the header is special, no
+ * need to set the header.
*/
- private boolean checkSpecialHeader( String name, String value) {
+ private boolean checkSpecialHeader(String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
- if( name.equalsIgnoreCase( "Content-Type" ) ) {
- setContentType( value );
+ if (name.equalsIgnoreCase("Content-Type")) {
+ setContentType(value);
return true;
}
- if( name.equalsIgnoreCase( "Content-Length" ) ) {
+ if (name.equalsIgnoreCase("Content-Length")) {
try {
- long cL=Long.parseLong( value );
- setContentLength( cL );
+ long cL = Long.parseLong(value);
+ setContentLength(cL);
return true;
- } catch( NumberFormatException ex ) {
+ } catch (NumberFormatException ex) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what they're doing
return false;
@@ -443,9 +437,8 @@ public final class Response {
/**
- * Signal that we're done with the headers, and body will follow. Any
- * implementation needs to notify ContextManager, to allow interceptors to
- * fix headers.
+ * Signal that we're done with the headers, and body will follow. Any implementation needs to notify ContextManager,
+ * to allow interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
@@ -461,8 +454,7 @@ public final class Response {
}
/**
- * Called explicitly by user to set the Content-Language and the default
- * encoding.
+ * Called explicitly by user to set the Content-Language and the default encoding.
*
* @param locale The locale to use for this response
*/
@@ -484,8 +476,7 @@ public final class Response {
/**
* Return the content language.
*
- * @return The language code for the language currently associated with this
- * response
+ * @return The language code for the language currently associated with this response
*/
public String getContentLanguage() {
return contentLanguage;
@@ -493,13 +484,12 @@ public final class Response {
/**
- * Overrides the character encoding used in the body of the response. This
- * method must be called prior to writing output using getWriter().
+ * Overrides the character encoding used in the body of the response. This method must be called prior to writing
+ * output using getWriter().
*
* @param characterEncoding The name of character encoding.
*
- * @throws UnsupportedEncodingException If the specified name is not
- * recognised
+ * @throws UnsupportedEncodingException If the specified name is not recognised
*/
public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException {
if (isCommitted()) {
@@ -530,11 +520,8 @@ public final class Response {
/**
- * Sets the content type.
- *
- * This method must preserve any response charset that may already have
- * been set via a call to response.setContentType(), response.setLocale(),
- * or response.setCharacterEncoding().
+ * Sets the content type. This method must preserve any response charset that may already have been set via a call
+ * to response.setContentType(), response.setLocale(), or response.setCharacterEncoding().
*
* @param type the content type
*/
@@ -547,7 +534,7 @@ public final class Response {
MediaType m = null;
try {
- m = MediaType.parseMediaType(new StringReader(type));
+ m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
@@ -653,15 +640,14 @@ public final class Response {
}
// update counters
- contentWritten=0;
+ contentWritten = 0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*
- * @return The total number of bytes written to the response by the
- * application. This will not be the number of bytes written to the
- * network which may be more or less than this value.
+ * @return The total number of bytes written to the response by the application. This will not be the number of
+ * bytes written to the network which may be more or less than this value.
*/
public long getContentWritten() {
return contentWritten;
@@ -670,9 +656,8 @@ public final class Response {
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*
- * @param flush Should any remaining bytes be flushed before returning the
- * total? If {@code false} bytes remaining in the buffer will
- * not be included in the returned value
+ * @param flush Should any remaining bytes be flushed before returning the total? If {@code false} bytes remaining
+ * in the buffer will not be included in the returned value
*
* @return The total number of bytes written to the socket for this response
*/
@@ -684,9 +669,8 @@ public final class Response {
}
/*
- * State for non-blocking output is maintained here as it is the one point
- * easily reachable from the CoyoteOutputStream and the Processor which both
- * need access to state.
+ * State for non-blocking output is maintained here as it is the one point easily reachable from the
+ * CoyoteOutputStream and the Processor which both need access to state.
*/
volatile WriteListener listener;
// Ensures listener is only fired after a call is isReady()
@@ -702,20 +686,17 @@ public final class Response {
public void setWriteListener(WriteListener listener) {
if (listener == null) {
- throw new NullPointerException(
- sm.getString("response.nullWriteListener"));
+ throw new NullPointerException(sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
- throw new IllegalStateException(
- sm.getString("response.writeListenerSet"));
+ throw new IllegalStateException(sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
- // for async
+ // for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
- throw new IllegalStateException(
- sm.getString("response.notAsync"));
+ throw new IllegalStateException(sm.getString("response.notAsync"));
}
this.listener = listener;
diff --git a/java/org/apache/coyote/UpgradeProtocol.java b/java/org/apache/coyote/UpgradeProtocol.java
index bd80e83ef9..a70f12f342 100644
--- a/java/org/apache/coyote/UpgradeProtocol.java
+++ b/java/org/apache/coyote/UpgradeProtocol.java
@@ -23,87 +23,74 @@ import org.apache.tomcat.util.net.SocketWrapperBase;
public interface UpgradeProtocol {
/**
- * @param isSSLEnabled Is this for a connector that is configured to support
- * TLS. Some protocols (e.g. HTTP/2) only support HTTP
- * upgrade over non-secure connections.
- * @return The name that clients will use to request an upgrade to this
- * protocol via an HTTP/1.1 upgrade request or <code>null</code> if
- * upgrade via an HTTP/1.1 upgrade request is not supported.
+ * @param isSSLEnabled Is this for a connector that is configured to support TLS. Some protocols (e.g. HTTP/2) only
+ * support HTTP upgrade over non-secure connections.
+ *
+ * @return The name that clients will use to request an upgrade to this protocol via an HTTP/1.1 upgrade request or
+ * <code>null</code> if upgrade via an HTTP/1.1 upgrade request is not supported.
*/
public String getHttpUpgradeName(boolean isSSLEnabled);
/**
- * @return The byte sequence as listed in the IANA registry for this
- * protocol or <code>null</code> if upgrade via ALPN is not
- * supported.
+ * @return The byte sequence as listed in the IANA registry for this protocol or <code>null</code> if upgrade via
+ * ALPN is not supported.
*/
public byte[] getAlpnIdentifier();
/**
- * @return The name of the protocol as listed in the IANA registry if and
- * only if {@link #getAlpnIdentifier()} returns the UTF-8 encoding
- * of this name. If {@link #getAlpnIdentifier()} returns some other
- * byte sequence, then this method returns the empty string. If
- * upgrade via ALPN is not supported then <code>null</code> is
- * returned.
+ * @return The name of the protocol as listed in the IANA registry if and only if {@link #getAlpnIdentifier()}
+ * returns the UTF-8 encoding of this name. If {@link #getAlpnIdentifier()} returns some other byte
+ * sequence, then this method returns the empty string. If upgrade via ALPN is not supported then
+ * <code>null</code> is returned.
*/
/*
- * Implementation note: If Tomcat ever supports ALPN for a protocol where
- * the identifier is not the UTF-8 encoding of the name
- * then some refactoring is going to be required.
+ * Implementation note: If Tomcat ever supports ALPN for a protocol where the identifier is not the UTF-8 encoding
+ * of the name then some refactoring is going to be required.
*
- * Implementation note: Tomcat assumes that the UTF-8 encoding of this name
- * will not exceed 255 bytes. Tomcat's behaviour if
- * longer names are used is undefined.
+ * Implementation note: Tomcat assumes that the UTF-8 encoding of this name will not exceed 255 bytes. Tomcat's
+ * behaviour if longer names are used is undefined.
*/
public String getAlpnName();
/**
- * @param socketWrapper The socketWrapper for the connection that requires
- * a processor
- * @param adapter The Adapter instance that provides access to the standard
- * Engine/Host/Context/Wrapper processing chain
+ * @param socketWrapper The socketWrapper for the connection that requires a processor
+ * @param adapter The Adapter instance that provides access to the standard Engine/Host/Context/Wrapper
+ * processing chain
*
- * @return A processor instance for processing a connection using this
- * protocol.
+ * @return A processor instance for processing a connection using this protocol.
*/
public Processor getProcessor(SocketWrapperBase<?> socketWrapper, Adapter adapter);
/**
* @param socketWrapper The socket
- * @param adapter The Adapter to use to configure the new upgrade handler
- * @param request A copy (may be incomplete) of the request that triggered
- * the upgrade
+ * @param adapter The Adapter to use to configure the new upgrade handler
+ * @param request A copy (may be incomplete) of the request that triggered the upgrade
*
* @return An instance of the HTTP upgrade handler for this protocol
*/
- public InternalHttpUpgradeHandler getInternalUpgradeHandler(SocketWrapperBase<?> socketWrapper, Adapter adapter, Request request);
+ public InternalHttpUpgradeHandler getInternalUpgradeHandler(SocketWrapperBase<?> socketWrapper, Adapter adapter,
+ Request request);
/**
- * Allows the implementation to examine the request and accept or reject it
- * based on what it finds.
+ * Allows the implementation to examine the request and accept or reject it based on what it finds.
*
- * @param request The request that included an upgrade header for this
- * protocol
+ * @param request The request that included an upgrade header for this protocol
*
- * @return <code>true</code> if the request is accepted, otherwise
- * <code>false</code>
+ * @return <code>true</code> if the request is accepted, otherwise <code>false</code>
*/
public boolean accept(Request request);
/**
- * Configure the HTTP/1.1 protocol that this UpgradeProcotol is nested
- * under. Connections passed to this UpgradeProtocol via HTTP upgrade will
- * have been initially handled by this HTTP/1.1 protocol implementation.
+ * Configure the HTTP/1.1 protocol that this UpgradeProcotol is nested under. Connections passed to this
+ * UpgradeProtocol via HTTP upgrade will have been initially handled by this HTTP/1.1 protocol implementation.
* <p>
* The default implementation is a NO-OP.
*
- * @param protocol The HTTP/1.1 protocol implementation that will initially
- * handle any connections passed to this UpgradeProtocol via
- * the HTTP upgrade mechanism
+ * @param protocol The HTTP/1.1 protocol implementation that will initially handle any connections passed to this
+ * UpgradeProtocol via the HTTP upgrade mechanism
*/
public default void setHttp11Protocol(AbstractHttp11Protocol<?> protocol) {
// NO-OP
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org