From 7345224a01eea4d0732454cfd5fff2a3cb300ee9 Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 15:37:53 +0200 Subject: [PATCH 01/11] Add poms for running Servlet 6 TCK Signed-off-by: Arjan Tijms --- appserver/tests/tck/servlet/pom.xml | 320 ++++++++++++++++++ .../tck-download/jakarta-servlet-tck/pom.xml | 82 +++++ 2 files changed, 402 insertions(+) create mode 100644 appserver/tests/tck/servlet/pom.xml create mode 100644 appserver/tests/tck/tck-download/jakarta-servlet-tck/pom.xml diff --git a/appserver/tests/tck/servlet/pom.xml b/appserver/tests/tck/servlet/pom.xml new file mode 100644 index 00000000000..2f4fd6ed64d --- /dev/null +++ b/appserver/tests/tck/servlet/pom.xml @@ -0,0 +1,320 @@ + + + + + 4.0.0 + + + org.glassfish.main.tests.tck + tck + 7.0.0-SNAPSHOT + + + glassfish-external-tck-servlet + pom + + TCK: servlet + + + ${project.build.directory}/apache-ant-${ant.version} + https://archive.apache.org/dist/ant/binaries/apache-ant-${ant.version}-bin.zip + + ${project.build.directory}/servlet-tck + ${tck.home}/src/com/sun/ts/tests + + ${project.build.directory}/glassfish7 + ${project.version} + ${glassfish.home}/glassfish/bin/asadmin + + org/glassfish/**\:com/sun/enterprise/** + + 14848 + 11527 + 18080 + 18181 + 17676 + 18686 + 13700 + 13920 + 13820 + 12000 + + + + + org.glassfish.main.distributions + glassfish + ${glassfish.version} + zip + test + + + org.glassfish.main.tests.tck + jakarta-servlet-tck + ${project.version} + zip + + + + + + + com.googlecode.maven-download-plugin + download-maven-plugin + + + download-ant + generate-resources + + wget + + + + + ${skipITs} + ${ant.zip.url} + true + ${project.build.directory} + + + + + maven-dependency-plugin + + ${skipITs} + + + + unpack-glassfish + pre-integration-test + + unpack-dependencies + + + glassfish + ${project.build.directory} + + + + unpack-tck + pre-integration-test + + unpack-dependencies + + + jakarta-servlet-tck + ${project.build.directory} + + + + + + + maven-antrun-plugin + + + org.apache.ant + ant + ${ant.version} + + + ant-contrib + ant-contrib + 1.0b3 + + + ant + ant + + + + + + ${skipITs} + + + + prepare-tck-and-glassfish + pre-integration-test + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + + ]]> + + + + ]]> + + ]]> + + + + + run + + + + + configure-tck-tests + pre-integration-test + + run + + + + + + + + + + + + + + + + + + + + + + Deploying from ${test.dir} + + + + + + + + + + + + + + + + + + run-tck-tests + integration-test + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/appserver/tests/tck/tck-download/jakarta-servlet-tck/pom.xml b/appserver/tests/tck/tck-download/jakarta-servlet-tck/pom.xml new file mode 100644 index 00000000000..4afc4bc1282 --- /dev/null +++ b/appserver/tests/tck/tck-download/jakarta-servlet-tck/pom.xml @@ -0,0 +1,82 @@ + + + + 4.0.0 + + org.glassfish.main.tests.tck + tck-download + 7.0.0-SNAPSHOT + + + jakarta-servlet-tck + pom + TCK: Install Jakarta servlet TCK + + + jakarta-servlet-tck-6.0.0.zip + https://download.eclipse.org/ee4j/jakartaee-tck/jakartaee10/staged/eftl/${tck.test.servlet.file} + + + + + + com.googlecode.maven-download-plugin + download-maven-plugin + + + download-servlet-tck + generate-resources + + wget + + + + + ${tck.test.servlet.url} + false + ${project.build.directory} + + + + maven-install-plugin + + + install-servlet-tck + process-resources + + install-file + + + ${project.build.directory}/${tck.test.servlet.file} + ${project.groupId} + ${project.artifactId} + ${project.version} + zip + true + + + + + + + + From e42888d3fbebd85d29ac0857c049add57f900042 Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 15:40:33 +0200 Subject: [PATCH 02/11] Remove restriction from some methods according to Servlet 6 rules Signed-off-by: Arjan Tijms --- .../catalina/core/ApplicationContext.java | 77 +------------------ 1 file changed, 4 insertions(+), 73 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContext.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContext.java index 4eb84a1aa16..14e20c42e15 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContext.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationContext.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -93,16 +94,6 @@ public StandardContext getStandardContext() { } - // ----------------------------------------------------- Class Variables - - // START PWC 1.2 - /* - private static final SecurityPermission GET_UNWRAPPED_CONTEXT_PERMISSION = - new SecurityPermission("getUnwrappedContext"); - */ - // END PWC 1.2 - - // ----------------------------------------------------- Instance Variables /** @@ -243,7 +234,7 @@ public String getInitParameter(final String name) { */ @Override public Enumeration getInitParameterNames() { - return (new Enumerator(parameters.keySet())); + return new Enumerator(parameters.keySet()); } /** @@ -267,7 +258,7 @@ public boolean setInitParameter(String name, String value) { */ @Override public int getMajorVersion() { - return (Constants.MAJOR_VERSION); + return Constants.MAJOR_VERSION; } /** @@ -275,7 +266,7 @@ public int getMajorVersion() { */ @Override public int getMinorVersion() { - return (Constants.MINOR_VERSION); + return Constants.MINOR_VERSION; } /** @@ -284,10 +275,6 @@ public int getMinorVersion() { */ @Override public int getEffectiveMajorVersion() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getEffectiveMajorVersion(); } @@ -297,10 +284,6 @@ public int getEffectiveMajorVersion() { */ @Override public int getEffectiveMinorVersion() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getEffectiveMinorVersion(); } @@ -803,10 +786,6 @@ public void setSessionTrackingModes( */ @Override public Set getDefaultSessionTrackingModes() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getDefaultSessionTrackingModes(); } @@ -819,10 +798,6 @@ public Set getDefaultSessionTrackingModes() { */ @Override public Set getEffectiveSessionTrackingModes() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getEffectiveSessionTrackingModes(); } @@ -885,19 +860,11 @@ public T createListener(Class clazz) */ @Override public JspConfigDescriptor getJspConfigDescriptor() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getJspConfigDescriptor(); } @Override public ClassLoader getClassLoader() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getClassLoader(); } @@ -912,19 +879,11 @@ public void declareRoles(String... roleNames) { @Override public String getVirtualServerName() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getVirtualServerName(); } @Override public int getSessionTimeout() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getSessionTimeout(); } @@ -939,10 +898,6 @@ public void setSessionTimeout(int sessionTimeout) { @Override public String getRequestCharacterEncoding() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getRequestCharacterEncoding(); } @@ -957,10 +912,6 @@ public void setRequestCharacterEncoding(String encoding) { @Override public String getResponseCharacterEncoding() { - if (isRestricted) { - throw new UnsupportedOperationException( - rb.getString(LogFacade.UNSUPPORTED_OPERATION_EXCEPTION)); - } return context.getResponseCharacterEncoding(); } @@ -973,26 +924,6 @@ public void setResponseCharacterEncoding(String encoding) { context.setResponseCharacterEncoding(encoding); } - // START PWC 1.2 - /** - * Gets the underlying StandardContext to which this ApplicationContext is - * delegating. - * - * @return The underlying StandardContext - */ - /* - public StandardContext getUnwrappedContext() { - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(GET_UNWRAPPED_CONTEXT_PERMISSION); - } - - return this.context; - } - */ - // END PWC 1.2 - // -------------------------------------------------------- Package Methods From c781be77bde4572ad4a432a00613ba6b109214be Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 16:05:24 +0200 Subject: [PATCH 03/11] Refactoring of ResponseFacade Signed-off-by: Arjan Tijms --- .../catalina/connector/ResponseFacade.java | 405 ++++++------------ 1 file changed, 124 insertions(+), 281 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java index 29001be80ee..3defc3662eb 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -17,47 +18,51 @@ package org.apache.catalina.connector; -import org.apache.catalina.LogFacade; -import org.apache.catalina.security.SecurityUtil; +import static org.apache.catalina.LogFacade.NULL_RESPONSE_OBJECT; -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; -import java.security.*; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; +import org.apache.catalina.LogFacade; +import org.apache.catalina.security.SecurityUtil; + +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; /** - * Facade class that wraps a Coyote response object. - * All methods are delegated to the wrapped response. + * Facade class that wraps a Coyote response object. All methods are delegated to the wrapped response. * * @author Remy Maucherat * @author Jean-Francois Arcand - * @version $Revision: 1.9 $ $Date: 2007/05/05 05:32:43 $ */ - - -public class ResponseFacade - implements HttpServletResponse { +public class ResponseFacade implements HttpServletResponse { private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); + // ----------------------------------------------- Class/Instance Variables + /** + * The wrapped response. + */ + protected Response response; // ----------------------------------------------------------- DoPrivileged - private final class SetContentTypePrivilegedAction - implements PrivilegedAction { + private final class SetContentTypePrivilegedAction implements PrivilegedAction { private String contentType; - public SetContentTypePrivilegedAction(String contentType){ + public SetContentTypePrivilegedAction(String contentType) { this.contentType = contentType; } @@ -68,10 +73,8 @@ public Void run() { } } - // ----------------------------------------------------------- Constructors - /** * Construct a wrapper for the specified response. * @@ -81,19 +84,8 @@ public ResponseFacade(Response response) { this.response = response; } - - // ----------------------------------------------- Class/Instance Variables - - - /** - * The wrapped response. - */ - protected Response response = null; - - // --------------------------------------------------------- Public Methods - /** * Prevent cloning the facade. */ @@ -102,7 +94,6 @@ protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } - /** * Clear facade. */ @@ -110,119 +101,82 @@ public void clear() { response = null; } - public void finish() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); response.setSuspended(true); - } - public boolean isFinished() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.isSuspended(); } - // ------------------------------------------------ ServletResponse Methods @Override public String getCharacterEncoding() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.getCharacterEncoding(); } @Override public ServletOutputStream getOutputStream() throws IOException { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - // if (isFinished()) - // throw new IllegalStateException - // (/*sm.getString("responseFacade.finished")*/); + checkResponseNull(); ServletOutputStream sos = response.getOutputStream(); - if (isFinished()) + if (isFinished()) { response.setSuspended(true); - return (sos); + } + + return sos; } @Override public PrintWriter getWriter() throws IOException { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - // if (isFinished()) - // throw new IllegalStateException - // (/*sm.getString("responseFacade.finished")*/); + checkResponseNull(); PrintWriter writer = response.getWriter(); - if (isFinished()) + if (isFinished()) { response.setSuspended(true); - return (writer); + } + + return writer; } @Override public void setContentLength(int len) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setContentLength(len); } @Override public void setContentLengthLong(long len) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setContentLengthLong(len); } @Override public void setContentType(String type) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } - if (SecurityUtil.isPackageProtectionEnabled()){ + if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new SetContentTypePrivilegedAction(type)); } else { response.setContentType(type); @@ -231,405 +185,294 @@ public void setContentType(String type) { @Override public void setBufferSize(int size) { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.setBufferSize(size); } @Override public int getBufferSize() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.getBufferSize(); } @Override public void flushBuffer() throws IOException { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isFinished()) - // throw new IllegalStateException - // (/*sm.getString("responseFacade.finished")*/); + if (isFinished()) { return; + } - if (SecurityUtil.isPackageProtectionEnabled()){ - try{ - AccessController.doPrivileged( - new PrivilegedExceptionAction(){ + if (SecurityUtil.isPackageProtectionEnabled()) { + try { + AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override - public Void run() throws IOException{ + public Void run() throws IOException { response.setAppCommitted(true); response.flushBuffer(); return null; } }); - } catch(PrivilegedActionException e){ + } catch (PrivilegedActionException e) { Exception ex = e.getException(); - if (ex instanceof IOException){ - throw (IOException)ex; + if (ex instanceof IOException) { + throw (IOException) ex; } } } else { response.setAppCommitted(true); - response.flushBuffer(); } } @Override public void resetBuffer() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.resetBuffer(); } @Override public boolean isCommitted() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return (response.isAppCommitted()); } @Override public void reset() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.reset(); } @Override public void setLocale(Locale loc) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setLocale(loc); } @Override public Locale getLocale() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.getLocale(); } @Override public void addCookie(Cookie cookie) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.addCookie(cookie); } @Override public boolean containsHeader(String name) { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.containsHeader(name); } @Override public String encodeURL(String url) { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.encodeURL(url); } @Override public String encodeRedirectURL(String url) { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.encodeRedirectURL(url); } @Override public void sendError(int sc, String msg) throws IOException { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.setAppCommitted(true); - response.sendError(sc, msg); } @Override public void sendError(int sc) throws IOException { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.setAppCommitted(true); - response.sendError(sc); } @Override public void sendRedirect(String location) throws IOException { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) - throw new IllegalStateException - (/*sm.getString("responseBase.reset.ise")*/); + checkResponseNull(); + checkCommitted(); response.setAppCommitted(true); - response.sendRedirect(location); } @Override public void setDateHeader(String name, long date) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setDateHeader(name, date); } @Override public void addDateHeader(String name, long date) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.addDateHeader(name, date); } @Override public void setHeader(String name, String value) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setHeader(name, value); } @Override public void addHeader(String name, String value) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.addHeader(name, value); } @Override public void setIntHeader(String name, int value) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setIntHeader(name, value); } @Override public void addIntHeader(String name, int value) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.addIntHeader(name, value); } @Override public void setStatus(int sc) { + checkResponseNull(); - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } - - if (isCommitted()) + if (isCommitted()) { return; + } response.setStatus(sc); } @Override public String getContentType() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.getContentType(); } @Override public void setCharacterEncoding(String arg0) { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); response.setCharacterEncoding(arg0); } - - // START SJSAS 6374990 @Override public int getStatus() { - - // Disallow operation if the object has gone out of scope - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); return response.getStatus(); } - // END SJSAS 6374990 - @Override public String getHeader(String name) { - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); + return response.getHeader(name); } @Override public Collection getHeaders(String name) { - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); + return response.getHeaders(name); } @Override public Collection getHeaderNames() { - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); + return response.getHeaderNames(); } @Override public Supplier> getTrailerFields() { - if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); - } + checkResponseNull(); + return response.getTrailerFields(); } @Override public void setTrailerFields(Supplier> supplier) { + checkResponseNull(); + + response.setTrailerFields(supplier); + } + + private void checkResponseNull() { if (response == null) { - throw new IllegalStateException(rb.getString(LogFacade.NULL_RESPONSE_OBJECT)); + throw new IllegalStateException(rb.getString(NULL_RESPONSE_OBJECT)); } - response.setTrailerFields(supplier); } + + private void checkCommitted() { + if (isCommitted()) { + throw new IllegalStateException(); + } + } + } From 76a7d62d5b3c366ddc9c9d01fc22d9e5d5f4cff0 Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 16:41:38 +0200 Subject: [PATCH 04/11] Fix exception when getting writer with invalid charset Signed-off-by: Arjan Tijms --- .../catalina/connector/ResponseFacade.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java index 3defc3662eb..c18cbd6e124 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ResponseFacade.java @@ -22,6 +22,8 @@ import java.io.IOException; import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.UnsupportedCharsetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; @@ -138,12 +140,20 @@ public ServletOutputStream getOutputStream() throws IOException { public PrintWriter getWriter() throws IOException { checkResponseNull(); - PrintWriter writer = response.getWriter(); - if (isFinished()) { - response.setSuspended(true); - } + try { + PrintWriter writer = response.getWriter(); + if (isFinished()) { + response.setSuspended(true); + } - return writer; + return writer; + } catch (UnsupportedCharsetException e) { + // Servlet 6 states we should throw an UnsupportedEncodingException, but our backend + // naturally throws an UnsupportedCharsetException. + UnsupportedEncodingException unsupportedEncodingException = new UnsupportedEncodingException(); + unsupportedEncodingException.initCause(e); + throw unsupportedEncodingException; + } } @Override From 09555425c16f7a18428f174e608b90666f08f3cf Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 19:09:42 +0200 Subject: [PATCH 05/11] Refactoring Signed-off-by: Arjan Tijms --- .../apache/catalina/connector/Request.java | 2124 ++++++----------- 1 file changed, 685 insertions(+), 1439 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java index bdabcacaee2..c99c443587f 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -17,6 +18,52 @@ package org.apache.catalina.connector; +import static com.sun.logging.LogCleanerUtil.getSafeHeaderValue; +import static jakarta.servlet.DispatcherType.REQUEST; +import static jakarta.servlet.RequestDispatcher.ERROR_EXCEPTION; +import static jakarta.servlet.RequestDispatcher.INCLUDE_SERVLET_PATH; +import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static java.util.logging.Level.FINEST; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; +import static org.apache.catalina.Globals.CERTIFICATES_ATTR; +import static org.apache.catalina.Globals.CIPHER_SUITE_ATTR; +import static org.apache.catalina.Globals.DISPATCHER_TYPE_ATTR; +import static org.apache.catalina.Globals.ISO_8859_1_ENCODING; +import static org.apache.catalina.Globals.JREPLICA_PARAMETER; +import static org.apache.catalina.Globals.JREPLICA_SESSION_NOTE; +import static org.apache.catalina.Globals.KEY_SIZE_ATTR; +import static org.apache.catalina.Globals.REQUEST_FACADE_HELPER; +import static org.apache.catalina.Globals.SESSION_COOKIE_NAME; +import static org.apache.catalina.Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE; +import static org.apache.catalina.Globals.SESSION_VERSION_COOKIE_NAME; +import static org.apache.catalina.Globals.SESSION_VERSION_PARAMETER; +import static org.apache.catalina.Globals.SSL_SESSION_ID_ATTR; +import static org.apache.catalina.LogFacade.ALREADY_AUTHENTICATED; +import static org.apache.catalina.LogFacade.ASYNC_ALREADY_COMPLETE_EXCEPTION; +import static org.apache.catalina.LogFacade.ATTRIBUTE_EVENT_LISTENER_EXCEPTION; +import static org.apache.catalina.LogFacade.BREAKING_BACKGROUND_LOCK_EXCEPTION; +import static org.apache.catalina.LogFacade.GETINPUTSTREAM_BEEN_CALLED_EXCEPTION; +import static org.apache.catalina.LogFacade.INTERNAL_LOGOUT_ERROR; +import static org.apache.catalina.LogFacade.INVALID_URI_CHAR_ENCODING; +import static org.apache.catalina.LogFacade.INVALID_URI_ENCODING; +import static org.apache.catalina.LogFacade.LOGIN_WITH_AUTH_CONFIG; +import static org.apache.catalina.LogFacade.NO_AUTHENTICATOR; +import static org.apache.catalina.LogFacade.NULL_ATTRIBUTE_NAME_EXCEPTION; +import static org.apache.catalina.LogFacade.REQUEST_CALLED_WITHOUT_MULTIPART_CONFIG_EXCEPTION; +import static org.apache.catalina.LogFacade.REQUEST_NOT_PUT_INTO_ASYNC_MODE_EXCEPTION; +import static org.apache.catalina.LogFacade.REQUEST_WITHIN_SCOPE_OF_FILTER_OR_SERVLET_EXCEPTION; +import static org.apache.catalina.LogFacade.START_ASYNC_CALLED_AGAIN_EXCEPTION; +import static org.apache.catalina.LogFacade.START_ASYNC_CALLED_OUTSIDE_SCOPE_EXCEPTION; +import static org.apache.catalina.LogFacade.UNABLE_DETERMINE_CLIENT_ADDRESS; +import static org.apache.catalina.LogFacade.UNABLE_PERFORM_ERROR_DISPATCH; +import static org.apache.catalina.LogFacade.UNABLE_RESOLVE_IP_EXCEPTION; +import static org.apache.catalina.LogFacade.UNABLE_SET_REQUEST_CHARS; +import static org.apache.catalina.authenticator.Constants.REQ_SSOID_NOTE; +import static org.apache.catalina.authenticator.Constants.REQ_SSO_VERSION_NOTE; +import static org.apache.catalina.connector.Constants.AUTHORIZATION_HEADER; +import static org.apache.catalina.connector.Constants.JROUTE_COOKIE; + import java.io.BufferedReader; import java.io.CharConversionException; import java.io.File; @@ -35,44 +82,29 @@ import java.security.PrivilegedExceptionAction; import java.text.MessageFormat; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.EventListener; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; import java.util.logging.Logger; -import javax.security.auth.Subject; -import jakarta.servlet.AsyncContext; -import jakarta.servlet.DispatcherType; -import jakarta.servlet.FilterChain; -import jakarta.servlet.RequestDispatcher; -import jakarta.servlet.ServletConnection; -import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletInputStream; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletRequestAttributeEvent; -import jakarta.servlet.ServletRequestAttributeListener; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.SessionCookieConfig; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpSession; -import jakarta.servlet.http.HttpUpgradeHandler; -import jakarta.servlet.http.Part; -import jakarta.servlet.http.PushBuilder; -import jakarta.servlet.http.WebConnection; -import com.sun.appserv.ProxyHandler; -import jakarta.servlet.http.MappingMatch; +import javax.security.auth.Subject; -import static com.sun.logging.LogCleanerUtil.neutralizeForLog; import org.apache.catalina.Context; -import org.apache.catalina.LogFacade; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.HttpRequest; import org.apache.catalina.HttpResponse; +import org.apache.catalina.LogFacade; import org.apache.catalina.Manager; import org.apache.catalina.Pipeline; import org.apache.catalina.Realm; @@ -88,7 +120,9 @@ import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.session.PersistentManagerBase; import org.apache.catalina.session.StandardSession; -import org.apache.catalina.util.*; +import org.apache.catalina.util.Enumerator; +import org.apache.catalina.util.ParameterMap; +import org.apache.catalina.util.RequestUtil; import org.glassfish.grizzly.Buffer; import org.glassfish.grizzly.CompletionHandler; import org.glassfish.grizzly.EmptyCompletionHandler; @@ -106,8 +140,31 @@ import org.glassfish.grizzly.memory.Buffers; import org.glassfish.grizzly.utils.Charsets; import org.glassfish.web.valve.GlassFishValve; + +import com.sun.appserv.ProxyHandler; + +import jakarta.servlet.AsyncContext; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.FilterChain; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletConnection; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletRequestAttributeEvent; +import jakarta.servlet.ServletRequestAttributeListener; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.SessionCookieConfig; +import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletMapping; -import static com.sun.logging.LogCleanerUtil.getSafeHeaderValue; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpUpgradeHandler; +import jakarta.servlet.http.Part; +import jakarta.servlet.http.PushBuilder; +import jakarta.servlet.http.WebConnection; /** * Wrapper object for the Coyote request. @@ -117,8 +174,7 @@ * @author Rajiv Mordani * @version $Revision: 1.67.2.9 $ $Date: 2008/04/17 18:37:34 $ */ -public class Request - implements HttpRequest, HttpServletRequest { +public class Request implements HttpRequest, HttpServletRequest { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); @@ -127,214 +183,204 @@ public class Request /** * Descriptive information about this Request implementation. */ - protected static final String info = - "org.apache.catalina.connector.Request/1.0"; + protected static final String info = "org.apache.catalina.connector.Request/1.0"; /** * Whether or not to enforce scope checking of this object. */ - private static boolean enforceScope = false; + private static boolean enforceScope; - /** - * The notes key for the password used to authenticate this user. - */ - private static final String SESS_PASSWORD_NOTE = - "org.apache.catalina.session.PASSWORD"; - - - /** - * The notes key for the username used to authenticate this user. - */ - private static final String SESS_USERNAME_NOTE = - "org.apache.catalina.session.USERNAME"; - - // END CR 6309511 - // START OF SJSAS 6231069 - /* - protected SimpleDateFormat formats[] = { - new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), - new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), - new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) - }*/ /** * The set of SimpleDateFormat formats to use in getDateHeader(). * - * Notice that because SimpleDateFormat is not thread-safe, we can't - * declare formats[] as a static variable. + * Notice that because SimpleDateFormat is not thread-safe, we can't declare formats[] as a static variable. */ - private static ThreadLocal staticDateFormats = new ThreadLocal() { + private static ThreadLocal staticDateFormats = new ThreadLocal<>() { @Override protected Object initialValue() { SimpleDateFormat[] f = new SimpleDateFormat[3]; - f[0] = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", - Locale.US); - f[1] = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", - Locale.US); + f[0] = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); + f[1] = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US); f[2] = new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US); return f; } }; protected SimpleDateFormat formats[]; - // END OF SJSAS 6231069 + /** - * ThreadLocal object to keep track of the reentrancy status of each thread. - * It contains a byte[] object whose single element is either 0 (initial - * value or no reentrancy), or 1 (current thread is reentrant). When a - * thread exits the implies method, byte[0] is alwasy reset to 0. + * ThreadLocal object to keep track of the reentrancy status of each thread. It contains a byte[] object whose single + * element is either 0 (initial value or no reentrancy), or 1 (current thread is reentrant). When a thread exits the + * implies method, byte[0] is alwasy reset to 0. */ - private static ThreadLocal reentrancyStatus; - - static { - reentrancyStatus = new ThreadLocal() { + private static ThreadLocal reentrancyStatus = new ThreadLocal<>() { + @Override + protected synchronized Object initialValue() { + return new byte[] { 0 }; + } + }; - @Override - protected synchronized Object initialValue() { - return new byte[]{0}; - } - }; - } // ----------------------------------------------------- Instance Variables - /** * The set of cookies associated with this Request. */ - protected ArrayList cookies = new ArrayList(); + protected ArrayList cookies = new ArrayList<>(); + /** * The default Locale if none are specified. */ protected static final Locale defaultLocale = Locale.getDefault(); + /** * The attributes associated with this Request, keyed by attribute name. */ - protected Map attributes = new HashMap(); + protected Map attributes = new HashMap<>(); + /** * The preferred Locales associated with this Request. */ - protected ArrayList locales = new ArrayList(); + protected ArrayList locales = new ArrayList<>(); + /** - * Internal notes associated with this request by Catalina components - * and event listeners. + * Internal notes associated with this request by Catalina components and event listeners. */ - private Map notes = new HashMap(); + private Map notes = new HashMap<>(); + /** * Authentication type. */ - protected String authType = null; + protected String authType; + /** * The current dispatcher type. */ - protected Object dispatcherTypeAttr = null; + protected Object dispatcherTypeAttr; + /** * The associated input buffer. */ protected InputBuffer inputBuffer = new InputBuffer(); + /** * ServletInputStream. */ - protected CoyoteInputStream inputStream = - new CoyoteInputStream(inputBuffer); + protected CoyoteInputStream inputStream = new CoyoteInputStream(inputBuffer); + /** * Reader. */ protected CoyoteReader reader = new CoyoteReader(inputBuffer); + /** * Using stream flag. */ - protected boolean usingInputStream = false; + protected boolean usingInputStream; + /** * Using writer flag. */ - protected boolean usingReader = false; + protected boolean usingReader; + /** * User principal. */ - protected Principal userPrincipal = null; + protected Principal userPrincipal; + /** * Session parsed flag. */ - protected boolean sessionParsed = false; + protected boolean sessionParsed; + + protected boolean parametersProcessed; - protected boolean parametersProcessed = false; /** * Cookies parsed flag. */ - protected boolean cookiesParsed = false; + protected boolean cookiesParsed; + /** * Secure flag. */ - protected boolean secure = false; + protected boolean secure; + /** * The Subject associated with the current AccessControllerContext */ - protected Subject subject = null; + protected Subject subject; /** * Post data buffer. */ protected static final int CACHED_POST_LEN = 8192; - protected byte[] postData = null; + protected byte[] postData; /** * Hash map used in the getParametersMap method. */ - protected ParameterMap parameterMap = new ParameterMap(); + protected ParameterMap parameterMap = new ParameterMap<>(); + /** * The currently active session for this request. */ - protected Session session = null; + protected Session session; + /** * The current request dispatcher path. */ - protected Object requestDispatcherPath = null; + protected Object requestDispatcherPath; + /** * Was the requested session ID received in a cookie? */ - protected boolean requestedSessionCookie = false; + protected boolean requestedSessionCookie; + /** * The requested session ID (if any) for this request. */ - protected String requestedSessionId = null; + protected String requestedSessionId; /** * The requested session version (if any) for this request. */ - protected String requestedSessionVersion = null; + protected String requestedSessionVersion; private boolean isRequestedSessionIdFromSecureCookie; - // The requested session cookie path, see IT 7426 + // The requested session cookie path protected String requestedSessionCookiePath; // Temporary holder for URI params from which session id is parsed protected CharChunk uriParamsCC = new CharChunk(); + /** * Was the requested session ID received in a URL? */ - protected boolean requestedSessionURL = false; + protected boolean requestedSessionURL; + /** * The socket through which this Request was received. */ - protected Socket socket = null; + protected Socket socket; + /** * Parse locales. */ - protected boolean localesParsed = false; - /** - * The string parser we will use for parsing request lines. - */ - private StringParser parser = new StringParser(); + protected boolean localesParsed; + /** * Local port */ protected int localPort = -1; + /** * Remote address. */ - protected String remoteAddr = null; + protected String remoteAddr; + /** * Remote host. */ - protected String remoteHost = null; + protected String remoteHost; + /** * Remote port */ @@ -342,90 +388,83 @@ protected synchronized Object initialValue() { /** * Local address */ - protected String localName = null; + protected String localName; /** * Local address */ - protected String localAddr = null; - /** After the request is mapped to a ServletContext, we can also - * map it to a logger. - */ - /* CR 6309511 - protected Log log=null; - */ - // START CR 6415120 + protected String localAddr; + /** - * Whether or not access to resources in WEB-INF or META-INF needs to be - * checked. + * Whether or not access to resources in WEB-INF or META-INF needs to be checked. */ protected boolean checkRestrictedResources = true; - // END CR 6415120 + /** * has findSession been called and returned null already */ - private boolean unsuccessfulSessionFind = false; + private boolean unsuccessfulSessionFind; /* - * Are we supposed to honor the unsuccessfulSessionFind flag? - * WS overrides this to false. + * Are we supposed to honor the unsuccessfulSessionFind flag? WS overrides this to false. */ protected boolean checkUnsuccessfulSessionFind = true; - // START S1AS 4703023 + /** * The current application dispatch depth. */ private int dispatchDepth = 0; + /** * The maximum allowed application dispatch depth. */ private static int maxDispatchDepth = Constants.DEFAULT_MAX_DISPATCH_DEPTH; - // END S1AS 4703023 - // START SJSAS 6346226 private String jrouteId; - // END SJSAS 6346226 - // START GlassFish 896 private SessionTracker sessionTracker = new SessionTracker(); - // END GlassFish 896 - // START GlassFish 1024 - private boolean isDefaultContext = false; - // END GlassFish 1024 - private String requestURI = null; + private boolean isDefaultContext; + private String requestURI; + /** * Coyote request. */ protected org.glassfish.grizzly.http.server.Request coyoteRequest; + /** * The facade associated with this request. */ - protected RequestFacade facade = null; + protected RequestFacade facade; + /** - * Request facade that masks the fact that a request received - * at the root context was mapped to a default-web-module (if such a - * mapping exists). - * For example, its getContextPath() will return "/" rather than the - * context root of the default-web-module. + * Request facade that masks the fact that a request received at the root context was mapped to a default-web-module (if + * such a mapping exists). For example, its getContextPath() will return "/" rather than the context root of the + * default-web-module. */ - protected RequestFacade defaultContextMaskingFacade = null; + protected RequestFacade defaultContextMaskingFacade; + /** * The response with which this request is associated. */ - protected org.apache.catalina.Response response = null; + protected org.apache.catalina.Response response; + /** * Associated Catalina connector. */ protected org.apache.catalina.Connector connector; + /** * Mapping data. */ protected MappingData mappingData = new MappingData(); + /** * Associated wrapper. */ - protected Wrapper wrapper = null; + protected Wrapper wrapper; + /** * Filter chain associated with the request. */ - protected FilterChain filterChain = null; + protected FilterChain filterChain; + /** * Async operation */ @@ -441,11 +480,12 @@ protected synchronized Object initialValue() { * Multi-Part support */ private Multipart multipart; + /** * Associated context. */ - protected Context context = null; - protected ServletContext servletContext = null; + protected Context context; + protected ServletContext servletContext; // Associated StandardHost valve for error dispatches protected GlassFishValve hostValve; @@ -456,19 +496,17 @@ protected synchronized Object initialValue() { private String servletPath; private String pathInfo; - private boolean initRequestFacadeHelper = false; + private boolean initRequestFacadeHelper; // Allow Grizzly to auto detect a remote close connection. - public final static boolean discardDisconnectEvent = - Boolean.getBoolean("org.glassfish.grizzly.discardDisconnect"); + public final static boolean discardDisconnectEvent = Boolean.getBoolean("org.glassfish.grizzly.discardDisconnect"); /* * An upgrade request is received */ - private boolean upgrade = false; - - private boolean afterService = false; - private boolean resume = false; + private boolean upgrade; + private boolean afterService; + private boolean resume; /* * The HttpUpgradeHandler to be used for upgrade request @@ -480,15 +518,12 @@ protected synchronized Object initialValue() { */ private WebConnection webConnection; - // ----------------------------------------------------------- Constructor public Request() { - // START OF SJSAS 6231069 formats = (SimpleDateFormat[]) staticDateFormats.get(); formats[0].setTimeZone(TimeZone.getTimeZone("GMT")); formats[1].setTimeZone(TimeZone.getTimeZone("GMT")); formats[2].setTimeZone(TimeZone.getTimeZone("GMT")); - // END OF SJSAS 6231069 } // --------------------------------------------------------- Public Methods @@ -518,12 +553,10 @@ public static void setEnforceScope(boolean enforce) { } /** - * Release all object references, and initialize instance variables, in - * preparation for reuse of this object. + * Release all object references, and initialize instance variables, in preparation for reuse of this object. */ @Override public void recycle() { - if (isAsyncStarted()) { return; } @@ -578,15 +611,12 @@ public void recycle() { requestedSessionCookiePath = null; requestedSessionURL = false; uriParamsCC.recycle(); - - // START GlassFish 896 sessionTracker.reset(); - // END GlassFish 896 - /* CR 6309511 - log = null; + /* + * CR 6309511 log = null; */ - dispatchDepth = 0; // S1AS 4703023 + dispatchDepth = 0; parameterMap.setLocked(false); parameterMap.clear(); @@ -659,7 +689,7 @@ public HttpUpgradeHandler getHttpUpgradeHandler() { */ @Override public String getAuthorization() { - return coyoteRequest.getHeader(Constants.AUTHORIZATION_HEADER); + return coyoteRequest.getHeader(AUTHORIZATION_HEADER); } /** @@ -689,10 +719,9 @@ public Context getContext() { } /** - * Set the Context within which this Request is being processed. This - * must be called as soon as the appropriate Context is identified, because - * it identifies the value to be returned by getContextPath(), - * and thus enables parsing of the request URI. + * Set the Context within which this Request is being processed. This must be called as soon as the appropriate Context + * is identified, because it identifies the value to be returned by getContextPath(), and thus enables + * parsing of the request URI. * * @param context The newly associated Context */ @@ -716,26 +745,22 @@ public void setContext(Context context) { if (resEncoding != null) { getResponse().getResponse().setCharacterEncoding(resEncoding); } - } catch(UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } - // START GlassFish 896 + initSessionTracker(); - // END GlassFish 896 } - // START GlassFish 1024 /** - * @param isDefaultContext true if this request was mapped to a context - * with an empty context root that is backed by the vitual server's - * default-web-module + * @param isDefaultContext true if this request was mapped to a context with an empty context root that is backed by the + * vitual server's default-web-module */ public void setDefaultContext(boolean isDefaultContext) { this.isDefaultContext = isDefaultContext; } - // END GlassFish 1024 /** * Get filter chain associated with the request. @@ -764,9 +789,8 @@ public Host getHost() { } /** - * Set the Host within which this Request is being processed. This - * must be called as soon as the appropriate Host is identified, and - * before the Request is passed to a context. + * Set the Host within which this Request is being processed. This must be called as soon as the appropriate Host is + * identified, and before the Request is passed to a context. * * @param host The newly associated Host */ @@ -776,8 +800,7 @@ public void setHost(Host host) { } /** - * Return descriptive information about this Request implementation and - * the corresponding version number, in the format + * Return descriptive information about this Request implementation and the corresponding version number, in the format * <description>/<version>. */ @Override @@ -787,11 +810,9 @@ public String getInfo() { @Override public HttpServletMapping getHttpServletMapping() { - HttpServletMapping result; - - result = new MappingImpl(mappingData); - return result; + return new MappingImpl(mappingData); } + /** * Return mapping data. */ @@ -807,27 +828,23 @@ public void setMappingData(MappingData mappingData) { } /** - * Update this instance with the content of the {@link MappingData} - * {@link MappingData} + * Update this instance with the content of the {@link MappingData} {@link MappingData} */ - public void updatePaths(MappingData md) { + public void updatePaths(MappingData mappingData) { /* - * Save the path components of this request, in order for them to - * survive when the mapping data get recycled as the request - * returns to the container after it has been put into async mode. - * This is required to satisfy the requirements of subsequent async - * dispatches (or error dispatches, if the async operation times out, - * and no async listeners have been registered that could be notified - * at their onTimeout method) + * Save the path components of this request, in order for them to survive when the mapping data get recycled as the + * request returns to the container after it has been put into async mode. This is required to satisfy the requirements + * of subsequent async dispatches (or error dispatches, if the async operation times out, and no async listeners have + * been registered that could be notified at their onTimeout method) */ - pathInfo = md.pathInfo.toString(); - servletPath = md.wrapperPath.toString(); - contextPath = md.contextPath.toString(); + pathInfo = mappingData.pathInfo.toString(); + servletPath = mappingData.wrapperPath.toString(); + contextPath = mappingData.contextPath.toString(); } /** - * Gets the ServletRequest for which this object - * is the facade. This method must be implemented by a subclass. + * Gets the ServletRequest for which this object is the facade. This method must be implemented by a + * subclass. */ @Override public HttpServletRequest getRequest() { @@ -835,12 +852,11 @@ public HttpServletRequest getRequest() { } /** - * Gets the ServletRequest for which this object - * is the facade. This method must be implemented by a subclass. + * Gets the ServletRequest for which this object is the facade. This method must be implemented by a + * subclass. * - * @param maskDefaultContextMapping true if the fact that a request - * received at the root context was mapped to a default-web-module will - * be masked, false otherwise + * @param maskDefaultContextMapping true if the fact that a request received at the root context was mapped to a + * default-web-module will be masked, false otherwise */ @Override public HttpServletRequest getRequest(boolean maskDefaultContextMapping) { @@ -850,24 +866,23 @@ public HttpServletRequest getRequest(boolean maskDefaultContextMapping) { } if (!initRequestFacadeHelper) { - attributes.put(Globals.REQUEST_FACADE_HELPER, - facade.getRequestFacadeHelper()); + attributes.put(REQUEST_FACADE_HELPER, facade.getRequestFacadeHelper()); initRequestFacadeHelper = true; } + return facade; - } else { - if (defaultContextMaskingFacade == null) { - defaultContextMaskingFacade = new RequestFacade(this, true); - } + } - if (!initRequestFacadeHelper) { - attributes.put(Globals.REQUEST_FACADE_HELPER, - defaultContextMaskingFacade.getRequestFacadeHelper()); - initRequestFacadeHelper = true; - } + if (defaultContextMaskingFacade == null) { + defaultContextMaskingFacade = new RequestFacade(this, true); + } - return defaultContextMaskingFacade; + if (!initRequestFacadeHelper) { + attributes.put(REQUEST_FACADE_HELPER, defaultContextMaskingFacade.getRequestFacadeHelper()); + initRequestFacadeHelper = true; } + + return defaultContextMaskingFacade; } /** @@ -875,7 +890,7 @@ public HttpServletRequest getRequest(boolean maskDefaultContextMapping) { */ @Override public org.apache.catalina.Response getResponse() { - return this.response; + return response; } /** @@ -892,10 +907,8 @@ public void setResponse(org.apache.catalina.Response response) { } /** - * Return the Socket (if any) through which this Request was received. - * This should only be used to access underlying state - * information about this Socket, such as the SSLSession associated with - * an SSLSocket. + * Return the Socket (if any) through which this Request was received. This should only be used to + * access underlying state information about this Socket, such as the SSLSession associated with an SSLSocket. */ @Override public Socket getSocket() { @@ -938,6 +951,7 @@ public InputStream getStream() { public void setStream(InputStream stream) { // Ignore } + /** * URI byte to char converter (not recycled). */ @@ -968,9 +982,9 @@ public Wrapper getWrapper() { } /** - * Set the Wrapper within which this Request is being processed. This - * must be called as soon as the appropriate Wrapper is identified, and - * before the Request is ultimately passed to an application servlet. + * Set the Wrapper within which this Request is being processed. This must be called as soon as the appropriate Wrapper + * is identified, and before the Request is ultimately passed to an application servlet. + * * @param wrapper The newly associated Wrapper */ @Override @@ -980,14 +994,12 @@ public void setWrapper(Wrapper wrapper) { // ------------------------------------------------- Request Public Methods /** - * Create and return a ServletInputStream to read the content - * associated with this Request. + * Create and return a ServletInputStream to read the content associated with this Request. * * @exception IOException if an input/output error occurs */ @Override - public ServletInputStream createInputStream() - throws IOException { + public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } @@ -995,8 +1007,7 @@ public ServletInputStream createInputStream() } /** - * Perform whatever actions are required to flush and close the input - * stream or reader, in a single operation. + * Perform whatever actions are required to flush and close the input stream or reader, in a single operation. * * @exception IOException if an input/output error occurs */ @@ -1006,8 +1017,8 @@ public void finishRequest() throws IOException { } /** - * Return the object bound with the specified name to the internal notes - * for this request, or null if no such binding exists. + * Return the object bound with the specified name to the internal notes for this request, or null if no + * such binding exists. * * @param name Name of the note to be returned */ @@ -1017,8 +1028,7 @@ public Object getNote(String name) { } /** - * Return an Iterator containing the String names of all notes bindings - * that exist for this request. + * Return an Iterator containing the String names of all notes bindings that exist for this request. */ @Override public Iterator getNoteNames() { @@ -1026,8 +1036,7 @@ public Iterator getNoteNames() { } /** - * Remove any object bound to the specified name in the internal notes - * for this request. + * Remove any object bound to the specified name in the internal notes for this request. * * @param name Name of the note to be removed */ @@ -1037,8 +1046,8 @@ public void removeNote(String name) { } /** - * Bind an object to a specified name in the internal notes associated - * with this request, replacing any existing binding for this name. + * Bind an object to a specified name in the internal notes associated with this request, replacing any existing binding + * for this name. * * @param name Name to which the object should be bound * @param value Object to be bound to the specified name @@ -1059,8 +1068,7 @@ public void setContentLength(int length) { } /** - * Set the content type (and optionally the character encoding) - * associated with this Request. For example, + * Set the content type (and optionally the character encoding) associated with this Request. For example, * text/html; charset=ISO-8859-4. * * @param type The new content type @@ -1091,8 +1099,7 @@ public void setRemoteAddr(String remoteAddr) { } /** - * Set the fully qualified name of the remote client associated with this - * Request. + * Set the fully qualified name of the remote client associated with this Request. * * @param remoteHost The remote host name */ @@ -1101,8 +1108,7 @@ public void setRemoteHost(String remoteHost) { } /** - * Set the value to be returned by isSecure() - * for this Request. + * Set the value to be returned by isSecure() for this Request. * * @param secure The new isSecure value */ @@ -1131,10 +1137,8 @@ public void setServerPort(int port) { coyoteRequest.setServerPort(port); } - // START CR 6415120 /** - * Set whether or not access to resources under WEB-INF or META-INF - * needs to be checked. + * Set whether or not access to resources under WEB-INF or META-INF needs to be checked. */ @Override public void setCheckRestrictedResources(boolean check) { @@ -1142,100 +1146,79 @@ public void setCheckRestrictedResources(boolean check) { } /** - * Return whether or not access to resources under WEB-INF or META-INF - * needs to be checked. + * Return whether or not access to resources under WEB-INF or META-INF needs to be checked. */ @Override public boolean getCheckRestrictedResources() { return this.checkRestrictedResources; } - // END CR 6415120 // ------------------------------------------------- ServletRequest Methods /** - * Return the specified request attribute if it exists; otherwise, return - * null. + * Return the specified request attribute if it exists; otherwise, return null. * * @param name Name of the request attribute to return */ @Override public Object getAttribute(String name) { - if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { - return dispatcherTypeAttr == null - ? DispatcherType.REQUEST - : dispatcherTypeAttr; - } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { - return requestDispatcherPath == null - ? getRequestPathMB().toString() - : requestDispatcherPath.toString(); - } else if (name.equals(Globals.CONSTRAINT_URI)) { - return getRequestPathMB() != null - ? getRequestPathMB().toString() : null; + if (name.equals(DISPATCHER_TYPE_ATTR)) { + return dispatcherTypeAttr == null ? REQUEST : dispatcherTypeAttr; } - Object attr = attributes.get(name); + if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { + return requestDispatcherPath == null ? getRequestPathMB().toString() : requestDispatcherPath.toString(); + } - if (attr != null) { - return attr; + if (name.equals(Globals.CONSTRAINT_URI)) { + return getRequestPathMB() != null ? getRequestPathMB().toString() : null; } - attr = coyoteRequest.getAttribute(name); - if (attr != null) { - return attr; + Object attribute = attributes.get(name); + + if (attribute != null) { + return attribute; } + + attribute = coyoteRequest.getAttribute(name); + if (attribute != null) { + return attribute; + } + if (Globals.SSL_CERTIFICATE_ATTR.equals(name)) { // @TODO Implement SSL rehandshake RequestUtils.populateCertificateAttribute(coyoteRequest); - attr = getAttribute(Globals.CERTIFICATES_ATTR); - if (attr != null) { - attributes.put(name, attr); + attribute = getAttribute(CERTIFICATES_ATTR); + if (attribute != null) { + attributes.put(name, attribute); } } else if (isSSLAttribute(name)) { - /* SJSAS 6419950 - coyoteRequest.action(ActionCode.ACTION_REQ_SSL_ATTRIBUTE, - coyoteRequest); - attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR); - if( attr != null) { - attributes.put(Globals.CERTIFICATES_ATTR, attr); - } - attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR); - if(attr != null) { - attributes.put(Globals.CIPHER_SUITE_ATTR, attr); - } - attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR); - if(attr != null) { - attributes.put(Globals.KEY_SIZE_ATTR, attr); - } - */ - // START SJSAS 6419950 RequestUtils.populateSSLAttributes(coyoteRequest); - // END SJSAS 6419950 - attr = attributes.get(name); + attribute = attributes.get(name); } - return attr; + + return attribute; } /** * Test if a given name is one of the special Servlet-spec SSL attributes. */ static boolean isSSLAttribute(String name) { - return Globals.CERTIFICATES_ATTR.equals(name) || - Globals.CIPHER_SUITE_ATTR.equals(name) || - Globals.KEY_SIZE_ATTR.equals(name) || - Globals.SSL_SESSION_ID_ATTR.equals(name); + return + CERTIFICATES_ATTR.equals(name) || CIPHER_SUITE_ATTR.equals(name) || + KEY_SIZE_ATTR.equals(name) || SSL_SESSION_ID_ATTR.equals(name); } /** - * Return the names of all request attributes for this Request, or an - * empty Enumeration if there are none. + * Return the names of all request attributes for this Request, or an empty Enumeration if there are none. */ @Override public Enumeration getAttributeNames() { if (isSecure()) { populateSSLAttributes(); } - return new Enumerator(attributes.keySet(), true); + + return new Enumerator<>(attributes.keySet(), true); } /** @@ -1271,17 +1254,14 @@ public String getContentType() { } /** - * Return the servlet input stream for this Request. The default - * implementation returns a servlet input stream created by - * createInputStream(). + * Return the servlet input stream for this Request. The default implementation returns a servlet input stream created + * by createInputStream(). * - * @exception IllegalStateException if getReader() has - * already been called for this request + * @exception IllegalStateException if getReader() has already been called for this request * @exception IOException if an input/output error occurs */ @Override public ServletInputStream getInputStream() throws IOException { - if (usingReader) { throw new IllegalStateException(rb.getString(LogFacade.GETREADER_BEEN_CALLED_EXCEPTION)); } @@ -1290,106 +1270,74 @@ public ServletInputStream getInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } - return inputStream; + return inputStream; } /** - * Return the preferred Locale that the client will accept content in, - * based on the value for the first Accept-Language header - * that was encountered. If the request did not specify a preferred - * language, the server's default Locale is returned. + * Return the preferred Locale that the client will accept content in, based on the value for the first + * Accept-Language header that was encountered. If the request did not specify a preferred language, the + * server's default Locale is returned. */ @Override public Locale getLocale() { return coyoteRequest.getLocale(); -// if (!localesParsed) { -// parseLocales(); -// } -// -// if (locales.size() > 0) { -// return locales.get(0); -// } else { -// return defaultLocale; -// } - } /** - * Return the set of preferred Locales that the client will accept - * content in, based on the values for any Accept-Language - * headers that were encountered. If the request did not specify a - * preferred language, the server's default Locale is returned. + * Return the set of preferred Locales that the client will accept content in, based on the values for any + * Accept-Language headers that were encountered. If the request did not specify a preferred language, the + * server's default Locale is returned. */ @Override public Enumeration getLocales() { - return new Enumerator(coyoteRequest.getLocales()); -// if (!localesParsed) { -// parseLocales(); -// } -// -// if (locales.size() > 0) { -// return (new Enumerator(locales)); -// } -// ArrayList results = new ArrayList(); -// results.add(defaultLocale); -// return (new Enumerator(results)); + return new Enumerator<>(coyoteRequest.getLocales()); } private void processParameters() { if (parametersProcessed) { return; } + getCharacterEncoding(); if (isMultipartConfigured() && getMethod().equalsIgnoreCase("POST")) { String contentType = getContentType(); - if (contentType != null && - contentType.startsWith("multipart/form-data")) { + if (contentType != null && contentType.startsWith("multipart/form-data")) { getMultipart().init(); } } + parametersProcessed = true; } /** - * Return the value of the specified request parameter, if any; otherwise, - * return null. If there is more than one value defined, - * return only the first one. + * Return the value of the specified request parameter, if any; otherwise, return null. If there is more + * than one value defined, return only the first one. * * @param name Name of the desired request parameter */ @Override public String getParameter(String name) { - -/* - if (!requestParametersParsed) { - parseRequestParameters(); - } -*/ processParameters(); return coyoteRequest.getParameter(name); } /** - * Returns a Map of the parameters of this request. - * Request parameters are extra information sent with the request. - * For HTTP servlets, parameters are contained in the query string - * or posted form data. + * Returns a Map of the parameters of this request. Request parameters are extra information sent with the + * request. For HTTP servlets, parameters are contained in the query string or posted form data. * - * @return A Map containing parameter names as keys - * and parameter values as map values. + * @return A Map containing parameter names as keys and parameter values as map values. */ @Override public Map getParameterMap() { - if (parameterMap.isLocked()) { return parameterMap; } - Enumeration e = getParameterNames(); - while (e.hasMoreElements()) { - String name = e.nextElement(); + Enumeration paramaterNames = getParameterNames(); + while (paramaterNames.hasMoreElements()) { + String name = paramaterNames.nextElement(); String[] values = getParameterValues(name); parameterMap.put(name, values); } @@ -1397,7 +1345,6 @@ public Map getParameterMap() { parameterMap.setLocked(true); return parameterMap; - } /** @@ -1405,29 +1352,18 @@ public Map getParameterMap() { */ @Override public Enumeration getParameterNames() { -/* - if (!requestParametersParsed) { - parseRequestParameters(); - } -*/ processParameters(); - return new Enumerator(coyoteRequest.getParameterNames()); + return new Enumerator<>(coyoteRequest.getParameterNames()); } /** - * Return the defined values for the specified request parameter, if any; - * otherwise, return null. + * Return the defined values for the specified request parameter, if any; otherwise, return null. * * @param name Name of the desired request parameter */ @Override public String[] getParameterValues(String name) { -/* - if (!requestParametersParsed) { - parseRequestParameters(); - } -*/ processParameters(); return coyoteRequest.getParameterValues(name); @@ -1442,27 +1378,23 @@ public String getProtocol() { } /** - * Read the Reader wrapping the input stream for this Request. The - * default implementation wraps a BufferedReader around the - * servlet input stream returned by createInputStream(). + * Read the Reader wrapping the input stream for this Request. The default implementation wraps a + * BufferedReader around the servlet input stream returned by createInputStream(). * - * @exception IllegalStateException if getInputStream() - * has already been called for this request + * @exception IllegalStateException if getInputStream() has already been called for this request * @exception IOException if an input/output error occurs */ @Override public BufferedReader getReader() throws IOException { - if (usingInputStream) { - throw new IllegalStateException(rb.getString(LogFacade.GETINPUTSTREAM_BEEN_CALLED_EXCEPTION)); + throw new IllegalStateException(rb.getString(GETINPUTSTREAM_BEEN_CALLED_EXCEPTION)); } usingReader = true; try { inputBuffer.checkConverter(); } catch (UnsupportedCharsetException uce) { - UnsupportedEncodingException uee = - new UnsupportedEncodingException(uce.getMessage()); + UnsupportedEncodingException uee = new UnsupportedEncodingException(uce.getMessage()); uee.initCause(uce); throw uee; } @@ -1470,6 +1402,7 @@ public BufferedReader getReader() throws IOException { if (reader == null) { reader = new CoyoteReader(inputBuffer); } + return reader; } @@ -1480,25 +1413,22 @@ public BufferedReader getReader() throws IOException { public String getRemoteAddr() { if (remoteAddr == null) { - // START SJSAS 6347215 if (connector.getAuthPassthroughEnabled() && connector.getProxyHandler() != null) { - remoteAddr = connector.getProxyHandler().getRemoteAddress( - getRequest()); - if (remoteAddr == null && log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, LogFacade.UNABLE_DETERMINE_CLIENT_ADDRESS); + remoteAddr = connector.getProxyHandler().getRemoteAddress(getRequest()); + if (remoteAddr == null && log.isLoggable(FINEST)) { + log.log(FINEST, UNABLE_DETERMINE_CLIENT_ADDRESS); } return remoteAddr; } - // END SJSAS 6347215 if (socket != null) { InetAddress inet = socket.getInetAddress(); remoteAddr = inet.getHostAddress(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest); remoteAddr = coyoteRequest.getRemoteAddr(); } } + return remoteAddr; } @@ -1510,35 +1440,31 @@ public String getRemoteHost() { if (remoteHost == null) { if (!connector.getEnableLookups()) { remoteHost = getRemoteAddr(); - // START SJSAS 6347215 } else if (connector.getAuthPassthroughEnabled() && connector.getProxyHandler() != null) { - String addr = - connector.getProxyHandler().getRemoteAddress(getRequest()); + String addr = connector.getProxyHandler().getRemoteAddress(getRequest()); if (addr != null) { try { remoteHost = InetAddress.getByName(addr).getHostName(); } catch (UnknownHostException e) { - String msg = MessageFormat.format(rb.getString(LogFacade.UNABLE_RESOLVE_IP_EXCEPTION), addr); - log.log(Level.WARNING, msg, e); + String msg = MessageFormat.format(rb.getString(UNABLE_RESOLVE_IP_EXCEPTION), addr); + log.log(WARNING, msg, e); } - } else if (log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, LogFacade.UNABLE_DETERMINE_CLIENT_ADDRESS); + } else if (log.isLoggable(FINEST)) { + log.log(FINEST, UNABLE_DETERMINE_CLIENT_ADDRESS); } - // END SJSAS 6347215 } else if (socket != null) { InetAddress inet = socket.getInetAddress(); remoteHost = inet.getHostName(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_HOST_ATTRIBUTE, coyoteRequest); remoteHost = coyoteRequest.getRemoteHost(); } } + return remoteHost; } /** - * Returns the Internet Protocol (IP) source port of the client - * or last proxy that sent the request. + * Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request. */ @Override public int getRemotePort() { @@ -1546,16 +1472,15 @@ public int getRemotePort() { if (socket != null) { remotePort = socket.getPort(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest); remotePort = coyoteRequest.getRemotePort(); } } + return remotePort; } /** - * Returns the host name of the Internet Protocol (IP) interface on - * which the request was received. + * Returns the host name of the Internet Protocol (IP) interface on which the request was received. */ @Override public String getLocalName() { @@ -1564,16 +1489,15 @@ public String getLocalName() { InetAddress inet = socket.getLocalAddress(); localName = inet.getHostName(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest); localName = coyoteRequest.getLocalName(); } } + return localName; } /** - * Returns the Internet Protocol (IP) address of the interface on - * which the request was received. + * Returns the Internet Protocol (IP) address of the interface on which the request was received. */ @Override public String getLocalAddr() { @@ -1582,16 +1506,15 @@ public String getLocalAddr() { InetAddress inet = socket.getLocalAddress(); localAddr = inet.getHostAddress(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest); localAddr = coyoteRequest.getLocalAddr(); } } + return localAddr; } /** - * Returns the Internet Protocol (IP) port number of the interface - * on which the request was received. + * Returns the Internet Protocol (IP) port number of the interface on which the request was received. */ @Override public int getLocalPort() { @@ -1599,22 +1522,21 @@ public int getLocalPort() { if (socket != null) { localPort = socket.getLocalPort(); } else { -// coyoteRequest.action(ActionCode.ACTION_REQ_LOCALPORT_ATTRIBUTE, coyoteRequest); localPort = coyoteRequest.getLocalPort(); } } + return localPort; } /** - * Return a RequestDispatcher that wraps the resource at the specified - * path, which may be interpreted as relative to the current request path. + * Return a RequestDispatcher that wraps the resource at the specified path, which may be interpreted as relative to the + * current request path. * * @param path Path of the resource to be wrapped */ @Override public RequestDispatcher getRequestDispatcher(String path) { - if (servletContext == null) { return null; } @@ -1622,37 +1544,37 @@ public RequestDispatcher getRequestDispatcher(String path) { // If the path is already context-relative, just pass it through if (path == null) { return null; - } else if (path.startsWith("/")) { + } + + if (path.startsWith("/")) { return servletContext.getRequestDispatcher(path); } // Convert a request-relative path to a context-relative one - String servPath = (String) getAttribute( - RequestDispatcher.INCLUDE_SERVLET_PATH); - if (servPath == null) { - servPath = getServletPath(); + String servletPath = (String) getAttribute(INCLUDE_SERVLET_PATH); + if (servletPath == null) { + servletPath = getServletPath(); } // Add the path info, if there is any - String pInfo = getPathInfo(); + String pathInfo = getPathInfo(); String requestPath = null; - if (pInfo == null) { - requestPath = servPath; + if (pathInfo == null) { + requestPath = servletPath; } else { - requestPath = servPath + pInfo; + requestPath = servletPath + pathInfo; } - int pos = requestPath.lastIndexOf('/'); - String relative = null; - if (pos >= 0) { - relative = requestPath.substring(0, pos + 1) + path; + int lastSlashPos = requestPath.lastIndexOf('/'); + String relativePath = null; + if (lastSlashPos >= 0) { + relativePath = requestPath.substring(0, lastSlashPos + 1) + path; } else { - relative = requestPath + path; + relativePath = requestPath + path; } - return servletContext.getRequestDispatcher(relative); - + return servletContext.getRequestDispatcher(relativePath); } /** @@ -1660,14 +1582,12 @@ public RequestDispatcher getRequestDispatcher(String path) { */ @Override public String getScheme() { - // START S1AS 6170450 if (getConnector() != null && getConnector().getAuthPassthroughEnabled()) { ProxyHandler proxyHandler = getConnector().getProxyHandler(); if (proxyHandler != null && proxyHandler.getSSLKeysize(getRequest()) > 0) { return "https"; } } - // END S1AS 6170450 return coyoteRequest.getScheme(); } @@ -1685,22 +1605,15 @@ public String getServerName() { */ @Override public int getServerPort() { - /* SJSAS 6586658 - return (coyoteRequest.getServerPort()); - */ - // START SJSAS 6586658 if (isSecure()) { String host = getHeader("host"); if (host != null && host.indexOf(':') == -1) { // No port number provided with Host header, use default return 443; - } else { - return coyoteRequest.getServerPort(); } - } else { - return coyoteRequest.getServerPort(); } - // END SJSAS 6586658 + + return coyoteRequest.getServerPort(); } /** @@ -1732,23 +1645,21 @@ public void removeAttribute(String name) { if (listeners.isEmpty()) { return; } - ServletRequestAttributeEvent event = - new ServletRequestAttributeEvent(servletContext, getRequest(), - name, value); + ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(servletContext, getRequest(), name, value); Iterator iter = listeners.iterator(); while (iter.hasNext()) { EventListener eventListener = iter.next(); if (!(eventListener instanceof ServletRequestAttributeListener)) { continue; } - ServletRequestAttributeListener listener = - (ServletRequestAttributeListener) eventListener; + + ServletRequestAttributeListener listener = (ServletRequestAttributeListener) eventListener; try { listener.attributeRemoved(event); } catch (Throwable t) { - log(rb.getString(LogFacade.ATTRIBUTE_EVENT_LISTENER_EXCEPTION), t); + log(rb.getString(ATTRIBUTE_EVENT_LISTENER_EXCEPTION), t); // Error valve will pick this exception up and display it to user - attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); + attributes.put(ERROR_EXCEPTION, t); } } } @@ -1761,10 +1672,9 @@ public void removeAttribute(String name) { */ @Override public void setAttribute(String name, Object value) { - // Name cannot be null if (name == null) { - throw new IllegalArgumentException(rb.getString(LogFacade.NULL_ATTRIBUTE_NAME_EXCEPTION)); + throw new IllegalArgumentException(rb.getString(NULL_ATTRIBUTE_NAME_EXCEPTION)); } // Null value is the same as removeAttribute() @@ -1773,7 +1683,7 @@ public void setAttribute(String name, Object value) { return; } - if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { + if (name.equals(DISPATCHER_TYPE_ATTR)) { dispatcherTypeAttr = value; return; } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { @@ -1784,8 +1694,7 @@ public void setAttribute(String name, Object value) { boolean replaced = false; // Do the security check before any updates are made - if (Globals.IS_SECURITY_ENABLED && - name.equals("org.apache.tomcat.sendfile.filename")) { + if (Globals.IS_SECURITY_ENABLED && name.equals("org.apache.tomcat.sendfile.filename")) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; @@ -1808,27 +1717,22 @@ public void setAttribute(String name, Object value) { replaced = true; } - // START SJSAS 6231069 - // Pass special attributes to the ngrizzly layer + // Pass special attributes to the grizzly layer if (name.startsWith("grizzly.")) { coyoteRequest.setAttribute(name, value); } - // END SJSAS 6231069 // Notify interested application event listeners List listeners = context.getApplicationEventListeners(); if (listeners.isEmpty()) { return; } + ServletRequestAttributeEvent event = null; if (replaced) { - event = new ServletRequestAttributeEvent(servletContext, - getRequest(), name, - oldValue); + event = new ServletRequestAttributeEvent(servletContext, getRequest(), name, oldValue); } else { - event = new ServletRequestAttributeEvent(servletContext, - getRequest(), name, - value); + event = new ServletRequestAttributeEvent(servletContext, getRequest(), name, value); } Iterator iter = listeners.iterator(); @@ -1837,8 +1741,7 @@ public void setAttribute(String name, Object value) { if (!(eventListener instanceof ServletRequestAttributeListener)) { continue; } - ServletRequestAttributeListener listener = - (ServletRequestAttributeListener) eventListener; + ServletRequestAttributeListener listener = (ServletRequestAttributeListener) eventListener; try { if (replaced) { listener.attributeReplaced(event); @@ -1846,54 +1749,37 @@ public void setAttribute(String name, Object value) { listener.attributeAdded(event); } } catch (Throwable t) { - log(rb.getString(LogFacade.ATTRIBUTE_EVENT_LISTENER_EXCEPTION), t); + log(rb.getString(ATTRIBUTE_EVENT_LISTENER_EXCEPTION), t); // Error valve will pick this exception up and display it to user - attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); + attributes.put(ERROR_EXCEPTION, t); } } } /** - * Overrides the name of the character encoding used in the body of this - * request. + * Overrides the name of the character encoding used in the body of this request. * - * This method must be called prior to reading request parameters or - * reading input using getReader(). Otherwise, it has no - * effect. + * This method must be called prior to reading request parameters or reading input using getReader(). + * Otherwise, it has no effect. * - * @param enc String containing the name of - * the character encoding. - * @throws UnsupportedEncodingException if this - * ServletRequest is still in a state where a - * character encoding may be set, but the specified - * encoding is invalid + * @param enc String containing the name of the character encoding. + * @throws UnsupportedEncodingException if this ServletRequest is still in a state where a character encoding may be + * set, but the specified encoding is invalid * * @since Servlet 2.3 */ @Override - public void setCharacterEncoding(String enc) - throws UnsupportedEncodingException { - - // START SJSAS 4936855 + public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (parametersProcessed || usingReader) { - String contextName = - getContext() != null ? getContext().getName() : "UNKNOWN"; - log.log(Level.WARNING, LogFacade.UNABLE_SET_REQUEST_CHARS, new Object[] {enc, contextName}); + String contextName = getContext() != null ? getContext().getName() : "UNKNOWN"; + log.log(WARNING, UNABLE_SET_REQUEST_CHARS, new Object[] { enc, contextName }); return; } - // END SJSAS 4936855 // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; - // START S1AS 6179607: Workaround for 6181598. Workaround should be - // removed once the underlying issue in J2SE has been fixed. - /* - * String dummy = new String(buffer, enc); - */ - // END S1AS 6179607 - // START S1AS 6179607 final byte[] finalBuffer = buffer; final String finalEnc = enc; if (Globals.IS_SECURITY_ENABLED) { @@ -1911,14 +1797,11 @@ public String run() throws UnsupportedEncodingException { } else { new String(buffer, RequestUtil.lookupCharset(enc)); } - // END S1AS 6179607 // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); - } - // START S1AS 4703023 /** * Static setter method for the maximum dispatch depth */ @@ -1950,20 +1833,11 @@ public int decrementDispatchDepth() { public boolean isMaxDispatchDepthReached() { return dispatchDepth > maxDispatchDepth; } - // END S1AS 4703023 // ---------------------------------------------------- HttpRequest Methods @Override - public boolean authenticate(HttpServletResponse response) - throws IOException, ServletException { - - //Issue 9650 - COmmenting this as required - /* if (getUserPrincipal() != null) { - throw new ServletException("Attempt to re-login while the " + - "user identity already exists"); - }*/ - - if (context == null) {//TODO: throw an exception + public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { + if (context == null) { throw new ServletException("Internal error: Context null"); } @@ -1975,17 +1849,16 @@ public boolean authenticate(HttpServletResponse response) byte[] alreadyCalled = (byte[]) reentrancyStatus.get(); if (alreadyCalled[0] == 1) { - //Re-entrancy from a JSR 196 module, so call the authenticate directly + // Re-entrancy from a Jakarta Authentication module, so call the authenticate directly try { - return authBase.authenticate(this, (HttpResponse) getResponse(), - context.getLoginConfig()); + return authBase.authenticate(this, (HttpResponse) getResponse(), context.getLoginConfig()); } catch (Exception ex) { throw new ServletException("Exception thrown while attempting to authenticate", ex); } } else { - //No re-entrancy, so call invokeAuthenticateDelegate to check if - //JSR196 module is present + // No re-entrancy, so call invokeAuthenticateDelegate to check if + // a Jakarta Authentication is present alreadyCalled[0] = 1; try { final Realm realm = context.getRealm(); @@ -1999,7 +1872,8 @@ public boolean authenticate(HttpServletResponse response) @Override public Boolean run() { try { - return Boolean.valueOf(realm.invokeAuthenticateDelegate(req, (HttpResponse) getResponse(), context, authBase, true)); + return Boolean.valueOf( + realm.invokeAuthenticateDelegate(req, (HttpResponse) getResponse(), context, authBase, true)); } catch (IOException ex) { throw new RuntimeException("Exception thrown while attempting to authenticate", ex); } @@ -2015,34 +1889,29 @@ public Boolean run() { } } finally { - //Reset the threadlocal re-entrancy check variable + // Reset the threadlocal re-entrancy check variable alreadyCalled[0] = 0; } } } @Override - public void login(final String username, final String password) - throws ServletException { + public void login(final String username, final String password) throws ServletException { login(username, password != null ? password.toCharArray() : null); } - public void login(final String username, final char[] password) - throws ServletException { + public void login(final String username, final char[] password) throws ServletException { final Realm realm = context.getRealm(); if (realm != null && realm.isSecurityExtensionEnabled(getServletContext())) { - throw new ServletException - (rb.getString(LogFacade.LOGIN_WITH_AUTH_CONFIG)); - } + throw new ServletException(rb.getString(LOGIN_WITH_AUTH_CONFIG)); + } - if (getAuthType() != null || getRemoteUser() != null || - getUserPrincipal() != null) { - throw new ServletException( - rb.getString(LogFacade.ALREADY_AUTHENTICATED)); + if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { + throw new ServletException(rb.getString(ALREADY_AUTHENTICATED)); } if (context.getAuthenticator() == null) { - throw new ServletException(rb.getString(LogFacade.NO_AUTHENTICATOR)); + throw new ServletException(rb.getString(NO_AUTHENTICATOR)); } context.getAuthenticator().login(username, password, this); @@ -2050,18 +1919,15 @@ public void login(final String username, final char[] password) @Override public void logout() throws ServletException { - Realm realm = (context == null ? null : context.getRealm()); if (realm == null) { if (getUserPrincipal() != null || getAuthType() != null) { - throw new ServletException( - rb.getString(LogFacade.INTERNAL_LOGOUT_ERROR)); + throw new ServletException(rb.getString(INTERNAL_LOGOUT_ERROR)); } return; } - /* - * Pass the request (this). - */ + + // Pass the request (this). realm.logout(this); } @@ -2072,7 +1938,6 @@ public void logout() throws ServletException { */ @Override public void addCookie(Cookie cookie) { - // For compatibility only if (!cookiesParsed) { parseCookies(); @@ -2093,8 +1958,8 @@ public void addHeader(String name, String value) { } /** - * Add a Locale to the set of preferred Locales for this Request. The - * first added Locale will be the first one returned by getLocales(). + * Add a Locale to the set of preferred Locales for this Request. The first added Locale will be the first one returned + * by getLocales(). * * @param locale The new preferred Locale */ @@ -2104,9 +1969,8 @@ public void addLocale(Locale locale) { } /** - * Add a parameter name and corresponding set of values to this Request. - * (This is used when restoring the original request on a form based - * login). + * Add a parameter name and corresponding set of values to this Request. (This is used when restoring the original + * request on a form based login). * * @param name Name of this request parameter * @param values Corresponding values for this request parameter @@ -2142,14 +2006,12 @@ public void clearLocales() { } /** - * Clear the collection of parameters associated with this Request - * and reset the query string encoding charset. + * Clear the collection of parameters associated with this Request and reset the query string encoding charset. */ @Override public void clearParameters() { coyoteRequest.getParameters().recycle(); - coyoteRequest.getParameters().setQueryStringEncoding( - Charsets.lookupCharset(getConnector().getURIEncoding())); + coyoteRequest.getParameters().setQueryStringEncoding(Charsets.lookupCharset(getConnector().getURIEncoding())); } @Override @@ -2158,14 +2020,12 @@ public void replayPayload(byte[] payloadByteArray) { return; } - coyoteRequest.replayPayload(Buffers.wrap( - coyoteRequest.getContext().getMemoryManager(), payloadByteArray)); + coyoteRequest.replayPayload(Buffers.wrap(coyoteRequest.getContext().getMemoryManager(), payloadByteArray)); } /** - * Set the authentication type used for this request, if any; otherwise - * set the type to null. Typical values are "BASIC", - * "DIGEST", or "SSL". + * Set the authentication type used for this request, if any; otherwise set the type to null. Typical + * values are "BASIC", "DIGEST", or "SSL". * * @param type The authentication type used */ @@ -2177,8 +2037,8 @@ public void setAuthType(String type) { /** * Set the HTTP request method used for this Request. * - *

Used by FBL when the original request is restored after - * successful authentication. + *

+ * Used by FBL when the original request is restored after successful authentication. * * @param method The request method */ @@ -2190,8 +2050,8 @@ public void setMethod(String method) { /** * Sets the query string for this Request. * - *

Used by FBL when the original request is restored after - * successful authentication. + *

+ * Used by FBL when the original request is restored after successful authentication. * * @param query The query string */ @@ -2212,9 +2072,8 @@ public void setPathInfo(String pathInfo) { } /** - * Set a flag indicating whether or not the requested session ID for this - * request came in through a cookie. This is normally called by the - * HTTP Connector, when it parses the request headers. + * Set a flag indicating whether or not the requested session ID for this request came in through a cookie. This is + * normally called by the HTTP Connector, when it parses the request headers. * * @param flag The new flag */ @@ -2232,12 +2091,11 @@ public void setRequestedSessionCookiePath(String cookiePath) { } /** - * Set the requested session ID for this request. This is normally called - * by the HTTP Connector, when it parses the request headers. + * Set the requested session ID for this request. This is normally called by the HTTP Connector, when it parses the + * request headers. * - * This method, which is called when the session id is sent as a cookie, - * or when it is encoded in the request URL, removes a jvmRoute - * (if present) from the given id. + * This method, which is called when the session id is sent as a cookie, or when it is encoded in the request URL, + * removes a jvmRoute (if present) from the given id. * * @param id The new session id */ @@ -2263,9 +2121,8 @@ public void setRequestedSessionId(String id) { } /** - * Set a flag indicating whether or not the requested session ID for this - * request came in through a URL. This is normally called by the - * HTTP Connector, when it parses the request headers. + * Set a flag indicating whether or not the requested session ID for this request came in through a URL. This is + * normally called by the HTTP Connector, when it parses the request headers. * * @param flag The new flag */ @@ -2275,11 +2132,10 @@ public void setRequestedSessionURL(boolean flag) { } /** - * Set the unparsed request URI for this Request. This will normally be - * called by the HTTP Connector, when it parses the request headers. + * Set the unparsed request URI for this Request. This will normally be called by the HTTP Connector, when it parses the + * request headers. * - * Used by FBL when restoring original request after successful - * authentication. + * Used by FBL when restoring original request after successful authentication. * * @param uri The request URI */ @@ -2301,9 +2157,8 @@ public String getDecodedRequestURI() { /** * Gets the decoded request URI. * - * @param maskDefaultContextMapping true if the fact that a request - * received at the root context was mapped to a default-web-module will - * be masked, false otherwise + * @param maskDefaultContextMapping true if the fact that a request received at the root context was mapped to a + * default-web-module will be masked, false otherwise */ public String getDecodedRequestURI(boolean maskDefaultContextMapping) { try { @@ -2329,22 +2184,18 @@ public void setServletPath(String servletPath) { } /** - * Set the Principal who has been authenticated for this Request. This - * value is also used to calculate the value to be returned by the - * getRemoteUser() method. + * Set the Principal who has been authenticated for this Request. This value is also used to calculate the value to be + * returned by the getRemoteUser() method. * * @param principal The user Principal */ @Override public void setUserPrincipal(Principal principal) { - if (SecurityUtil.isPackageProtectionEnabled()) { HttpSession session = getSession(false); - if (subject != null && - !subject.getPrincipals().contains(principal)) { + if (subject != null && !subject.getPrincipals().contains(principal)) { subject.getPrincipals().add(principal); - } else if (session != null && - session.getAttribute(Globals.SUBJECT_ATTR) == null) { + } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { subject = new Subject(); subject.getPrincipals().add(principal); } @@ -2366,8 +2217,7 @@ public String getAuthType() { } /** - * Return the portion of the request URI used to select the Context - * of the Request. + * Return the portion of the request URI used to select the Context of the Request. */ @Override public String getContextPath() { @@ -2375,19 +2225,17 @@ public String getContextPath() { } /** - * Gets the portion of the request URI used to select the Context - * of the Request. + * Gets the portion of the request URI used to select the Context of the Request. * - * @param maskDefaultContextMapping true if the fact that a request - * received at the root context was mapped to a default-web-module will - * be masked, false otherwise + * @param maskDefaultContextMapping true if the fact that a request received at the root context was mapped to a + * default-web-module will be masked, false otherwise */ public String getContextPath(boolean maskDefaultContextMapping) { if (isDefaultContext && maskDefaultContextMapping) { return ""; - } else { - return contextPath; } + + return contextPath; } /** @@ -2395,7 +2243,6 @@ public String getContextPath(boolean maskDefaultContextMapping) { */ @Override public Cookie[] getCookies() { - if (!cookiesParsed) { parseCookies(); } @@ -2411,27 +2258,23 @@ public Cookie[] getCookies() { * Set the set of cookies received with this Request. */ public void setCookies(Cookie[] cookies) { - this.cookies.clear(); if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - this.cookies.add(cookies[i]); + for (Cookie element : cookies) { + this.cookies.add(element); } } } /** - * Return the value of the specified date header, if any; otherwise - * return -1. + * Return the value of the specified date header, if any; otherwise return -1. * * @param name Name of the requested date header * - * @exception IllegalArgumentException if the specified header value - * cannot be converted to a date + * @exception IllegalArgumentException if the specified header value cannot be converted to a date */ @Override public long getDateHeader(String name) { - String value = getHeader(name); if (value == null) { return -1L; @@ -2442,13 +2285,12 @@ public long getDateHeader(String name) { if (result != -1L) { return result; } - throw new IllegalArgumentException(value); + throw new IllegalArgumentException(value); } /** - * Return the first value of the specified header, if any; otherwise, - * return null + * Return the first value of the specified header, if any; otherwise, return null * * @param name Name of the requested header */ @@ -2458,14 +2300,13 @@ public String getHeader(String name) { } /** - * Return all of the values of the specified header, if any; otherwise, - * return an empty enumeration. + * Return all of the values of the specified header, if any; otherwise, return an empty enumeration. * * @param name Name of the requested header */ @Override public Enumeration getHeaders(String name) { - return new Enumerator(coyoteRequest.getHeaders(name).iterator()); + return new Enumerator<>(coyoteRequest.getHeaders(name).iterator()); } /** @@ -2473,28 +2314,24 @@ public Enumeration getHeaders(String name) { */ @Override public Enumeration getHeaderNames() { - return new Enumerator(coyoteRequest.getHeaderNames().iterator()); + return new Enumerator<>(coyoteRequest.getHeaderNames().iterator()); } /** - * Return the value of the specified header as an integer, or -1 if there - * is no such header for this request. + * Return the value of the specified header as an integer, or -1 if there is no such header for this request. * * @param name Name of the requested header * - * @exception IllegalArgumentException if the specified header value - * cannot be converted to an integer + * @exception IllegalArgumentException if the specified header value cannot be converted to an integer */ @Override public int getIntHeader(String name) { - String value = getHeader(name); if (value == null) { return -1; - } else { - return Integer.parseInt(value); } + return Integer.parseInt(value); } @Override @@ -2524,35 +2361,33 @@ public String getPathInfo() { } /** - * Return the extra path information for this request, translated - * to a real path. + * Return the extra path information for this request, translated to a real path. */ @Override public String getPathTranslated() { - if (servletContext == null) { return null; } if (getPathInfo() == null) { return null; - } else { - return servletContext.getRealPath(getPathInfo()); } + return servletContext.getRealPath(getPathInfo()); } @Override public PushBuilder newPushBuilder() { Http2Stream http2Stream = null; if (coyoteRequest != null) { - http2Stream = (Http2Stream)coyoteRequest.getAttribute(Http2Stream.HTTP2_STREAM_ATTRIBUTE); + http2Stream = (Http2Stream) coyoteRequest.getAttribute(Http2Stream.HTTP2_STREAM_ATTRIBUTE); } + if (http2Stream != null && http2Stream.isPushEnabled()) { return new ApplicationPushBuilder(this); - } else { - return null; } + + return null; } /** @@ -2564,22 +2399,21 @@ public String getQueryString() { if (queryString == null || "".equals(queryString)) { return null; - } else { - return queryString; } + + return queryString; } /** - * Return the name of the remote user that has been authenticated - * for this Request. + * Return the name of the remote user that has been authenticated for this Request. */ @Override public String getRemoteUser() { if (userPrincipal != null) { return userPrincipal.getName(); - } else { - return null; } + + return null; } /** @@ -2611,45 +2445,35 @@ public String getRequestURI() { /** * Gets the request URI for this request. * - * @param maskDefaultContextMapping true if the fact that a request - * received at the root context was mapped to a default-web-module will - * be masked, false otherwise + * @param maskDefaultContextMapping true if the fact that a request received at the root context was mapped to a + * default-web-module will be masked, false otherwise */ public String getRequestURI(boolean maskDefaultContextMapping) { if (maskDefaultContextMapping) { return coyoteRequest.getRequestURI(); - } else { - if (requestURI == null) { - // START GlassFish 1024 - if (isDefaultContext) { - requestURI = getContextPath() + - coyoteRequest.getRequestURI(); - } else { - // END GlassFish 1024 - requestURI = coyoteRequest.getRequestURI(); - // START GlassFish 1024 - } - // END GlassFish 1024 + } + + if (requestURI == null) { + if (isDefaultContext) { + requestURI = getContextPath() + coyoteRequest.getRequestURI(); + } else { + requestURI = coyoteRequest.getRequestURI(); } - return requestURI; } + + return requestURI; } /** - * Reconstructs the URL the client used to make the request. - * The returned URL contains a protocol, server name, port - * number, and server path, but it does not include query - * string parameters. + * Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port + * number, and server path, but it does not include query string parameters. *

- * Because this method returns a StringBuffer, - * not a String, you can modify the URL easily, + * Because this method returns a StringBuffer, not a String, you can modify the URL easily, * for example, to append query parameters. *

- * This method is useful for creating redirect messages and - * for reporting errors. + * This method is useful for creating redirect messages and for reporting errors. * - * @return A StringBuffer object containing the - * reconstructed URL + * @return A StringBuffer object containing the reconstructed URL */ @Override public StringBuffer getRequestURL() { @@ -2677,8 +2501,7 @@ public StringBuffer getRequestURL(boolean maskDefaultContextMapping) { } /** - * Return the portion of the request URI used to select the servlet - * that will process this request. + * Return the portion of the request URI used to select the servlet that will process this request. */ @Override public String getServletPath() { @@ -2686,33 +2509,31 @@ public String getServletPath() { } /** - * Return the session associated with this Request, creating one - * if necessary. + * Return the session associated with this Request, creating one if necessary. */ @Override public HttpSession getSession() { Session session = doGetSession(true); - if (session != null) { - return session.getSession(); - } else { + if (session == null) { return null; } + + return session.getSession(); } /** - * Return the session associated with this Request, creating one - * if necessary and requested. + * Return the session associated with this Request, creating one if necessary and requested. * * @param create Create a new session if one does not exist */ @Override public HttpSession getSession(boolean create) { Session session = doGetSession(create); - if (session != null) { - return session.getSession(); - } else { + if (session == null) { return null; } + + return session.getSession(); } /** @@ -2725,70 +2546,55 @@ public void setSession(Session newSess) { } /** - * Return true if the session identifier included in this - * request came from a cookie. + * Return true if the session identifier included in this request came from a cookie. */ @Override public boolean isRequestedSessionIdFromCookie() { - - if (requestedSessionId != null) { - return requestedSessionCookie; - } else { + if (requestedSessionId == null) { return false; } + return requestedSessionCookie; } /** - * Return true if the session identifier included in this - * request came from the request URI. + * Return true if the session identifier included in this request came from the request URI. */ @Override public boolean isRequestedSessionIdFromURL() { - - if (requestedSessionId != null) { - return requestedSessionURL; - } else { + if (requestedSessionId == null) { return false; } + return requestedSessionURL; } /** - * Marks (or unmarks) this request as having a JSESSIONID cookie - * that is marked as secure + * Marks (or unmarks) this request as having a JSESSIONID cookie that is marked as secure * - * @param secure true if this request has a JSESSIONID cookie that is - * marked as secure, false otherwise + * @param secure true if this request has a JSESSIONID cookie that is marked as secure, false otherwise */ public void setRequestedSessionIdFromSecureCookie(boolean secure) { isRequestedSessionIdFromSecureCookie = secure; } - /** - * @return true if this request contains a JSESSIONID cookie that is - * marked as secure, false otherwise + * @return true if this request contains a JSESSIONID cookie that is marked as secure, false otherwise */ public boolean isRequestedSessionIdFromSecureCookie() { return isRequestedSessionIdFromSecureCookie; } /** - * Return true if the session identifier included in this - * request identifies a valid session. + * Return true if the session identifier included in this request identifies a valid session. */ @Override public boolean isRequestedSessionIdValid() { - if (requestedSessionId == null) { - return false; - } - if (context == null) { + if ((requestedSessionId == null) || (context == null)) { return false; } - if (session != null && - requestedSessionId.equals(session.getIdInternal())) { + if (session != null && requestedSessionId.equals(session.getIdInternal())) { return session.isValid(); } @@ -2796,51 +2602,45 @@ public boolean isRequestedSessionIdValid() { if (manager == null) { return false; } + Session localSession = null; try { if (manager.isSessionVersioningSupported()) { - localSession = manager.findSession(requestedSessionId, - requestedSessionVersion); + localSession = manager.findSession(requestedSessionId, requestedSessionVersion); } else { localSession = manager.findSession(requestedSessionId, this); } } catch (IOException e) { localSession = null; } + if (localSession != null && localSession.isValid()) { return true; - } else { - return false; } + return false; } /** - * Return true if the authenticated user principal - * possesses the specified role name. + * Return true if the authenticated user principal possesses the specified role name. * * @param role Role name to be validated */ @Override public boolean isUserInRole(String role) { - // BEGIN RIMOD 4949842 /* - * Must get userPrincipal through getUserPrincipal(), can't assume - * it has already been set since it may be coming from core. + * Must get userPrincipal through getUserPrincipal(), can't assume it has already been set since it may be coming from + * core. */ - Principal userPrincipal = this.getUserPrincipal(); - // END RIMOD 4949842 + Principal userPrincipal = getUserPrincipal(); // Have we got an authenticated principal at all? - if (userPrincipal == null) { - return false; - } - // Identify the Realm we will use for checking role assignments - if (context == null) { + if (userPrincipal == null || context == null) { return false; } + Realm realm = context.getRealm(); if (realm == null) { return false; @@ -2850,21 +2650,13 @@ public boolean isUserInRole(String role) { if (wrapper != null) { String realRole = wrapper.findSecurityReference(role); - //START SJSAS 6232464 - if (realRole != null && - //realm.hasRole(userPrincipal, realRole)) - realm.hasRole(this, (HttpResponse) response, - userPrincipal, realRole)) { + if (realRole != null && realm.hasRole(this, (HttpResponse) response, userPrincipal, realRole)) { return true; } } // Check for a role defined directly as a - - //return (realm.hasRole(userPrincipal, role)); - return realm.hasRole(this, (HttpResponse) response, - userPrincipal, role); - //END SJSAS 6232464 + return realm.hasRole(this, (HttpResponse) response, userPrincipal, role); } /** @@ -2876,19 +2668,16 @@ public Principal getUserPrincipal() { } /** - * Return the session associated with this Request, creating one - * if necessary. + * Return the session associated with this Request, creating one if necessary. */ public Session getSessionInternal() { return doGetSession(true); } /** - * Gets the session associated with this Request, creating one - * if necessary and requested. + * Gets the session associated with this Request, creating one if necessary and requested. * - * @param create true if a new session is to be created if one does not - * already exist, false otherwise + * @param create true if a new session is to be created if one does not already exist, false otherwise */ @Override public Session getSessionInternal(boolean create) { @@ -2896,13 +2685,11 @@ public Session getSessionInternal(boolean create) { } /** - * Change the session id of the current session associated with this - * request and return the new session id. + * Change the session id of the current session associated with this request and return the new session id. * * @return the new session id * - * @throws IllegalStateException if there is no session associated - * with the request + * @throws IllegalStateException if there is no session associated with the request * * @since Servlet 3.1 */ @@ -2931,8 +2718,8 @@ public String changeSessionId() { } /** - * This object does not implement a session ID generator. Provide - * a dummy implementation so that the default one will be used. + * This object does not implement a session ID generator. Provide a dummy implementation so that the default one will be + * used. */ @Override public String generateSessionId() { @@ -2940,11 +2727,9 @@ public String generateSessionId() { } /** - * Gets the servlet context to which this servlet request was last - * dispatched. + * Gets the servlet context to which this servlet request was last dispatched. * - * @return the servlet context to which this servlet request was last - * dispatched + * @return the servlet context to which this servlet request was last dispatched */ @Override public ServletContext getServletContext() { @@ -2952,16 +2737,15 @@ public ServletContext getServletContext() { } /** - * Create an instance of HttpUpgradeHandler for an given - * class and uses it for the http protocol upgrade processing. + * Create an instance of HttpUpgradeHandler for an given class and uses it for the http protocol upgrade + * processing. * * @param handlerClass The HttpUpgradeHandler class used for the upgrade. * * @return an instance of the HttpUpgradeHandler * * @exception IOException if an I/O error occurred during the upgrade - * @exception ServletException if the given clazz fails to be - * instantiated + * @exception ServletException if the given clazz fails to be instantiated * * @see jakarta.servlet.http.HttpUpgradeHandler * @see jakarta.servlet.http.WebConnection @@ -2969,15 +2753,14 @@ public ServletContext getServletContext() { * @since Servlet 3.1 */ @Override - public T upgrade(Class handlerClass) - throws IOException, ServletException { + public T upgrade(Class handlerClass) throws IOException, ServletException { upgrade = true; T handler = null; try { handler = ((StandardContext) getContext()).createHttpUpgradeHandlerInstance(handlerClass); - } catch(IOException | ServletException ise) { + } catch (IOException | ServletException ise) { throw ise; - } catch(Throwable t) { + } catch (Throwable t) { throw new ServletException(t); } httpUpgradeHandler = handler; @@ -2989,8 +2772,8 @@ public WebConnection getWebConnection() { return webConnection; } - public void setWebConnection(WebConnection wc) { - webConnection = wc; + public void setWebConnection(WebConnection webConnection) { + this.webConnection = webConnection; } // ------------------------------------------------------ Protected Methods @@ -3013,18 +2796,16 @@ protected Session doGetSession(boolean create) { // Return the requested session if it exists and is valid Manager manager = context.getManager(); if (manager == null) { - return null; // Sessions are not supported + return null; // Sessions are not supported } if (requestedSessionId != null) { if (!checkUnsuccessfulSessionFind || !unsuccessfulSessionFind) { try { if (manager.isSessionVersioningSupported()) { - session = manager.findSession(requestedSessionId, - requestedSessionVersion); - //XXX need to revisit + session = manager.findSession(requestedSessionId, requestedSessionVersion); + // XXX need to revisit if (session instanceof StandardSession) { - incrementSessionVersion((StandardSession) session, - context); + incrementSessionVersion((StandardSession) session, context); } } else { session = manager.findSession(requestedSessionId, this); @@ -3049,20 +2830,16 @@ protected Session doGetSession(boolean create) { if (!create) { return null; } - if (context != null && response != null && - context.getCookies() && - response.getResponse().isCommitted()) { + + if (context != null && response != null && context.getCookies() && response.getResponse().isCommitted()) { throw new IllegalStateException(rb.getString(LogFacade.CANNOT_CREATE_SESSION_EXCEPTION)); } - // START S1AS8PE 4817642 if (requestedSessionId != null && context.getReuseSessionID()) { session = manager.createSession(requestedSessionId); if (manager instanceof PersistentManagerBase) { ((PersistentManagerBase) manager).removeFromInvalidatedSessions(requestedSessionId); } - // END S1AS8PE 4817642 - // START GlassFish 896 } else if (sessionTracker.getActiveSessions() > 0) { synchronized (sessionTracker) { if (sessionTracker.getActiveSessions() > 0) { @@ -3073,10 +2850,7 @@ protected Session doGetSession(boolean create) { } } } - // END GlassFish 896 - // START S1AS8PE 4817642 } else { - // END S1AS8PE 4817642 // Use the connector's random number generator (if any) to generate // a session ID. Fallback to the default session ID generator if // the connector does not implement one. @@ -3086,33 +2860,26 @@ protected Session doGetSession(boolean create) { } else { session = manager.createSession(); } - // START S1AS8PE 4817642 } - // END S1AS8PE 4817642 StandardHost reqHost = (StandardHost) getHost(); if (reqHost != null) { SingleSignOn sso = reqHost.getSingleSignOn(); if (sso != null) { - String ssoId = (String) getNote( - org.apache.catalina.authenticator.Constants.REQ_SSOID_NOTE); + String ssoId = (String) getNote(REQ_SSOID_NOTE); if (ssoId != null) { long ssoVersion = 0L; - Long ssoVersionObj = (Long)getNote( - org.apache.catalina.authenticator.Constants.REQ_SSO_VERSION_NOTE); + Long ssoVersionObj = (Long) getNote(REQ_SSO_VERSION_NOTE); if (ssoVersionObj != null) { ssoVersion = ssoVersionObj.longValue(); } sso.associate(ssoId, ssoVersion, session); - removeNote( - org.apache.catalina.authenticator.Constants.REQ_SSOID_NOTE); + removeNote(REQ_SSOID_NOTE); } } } - // START GlassFish 896 sessionTracker.track(session); - // END GlassFish 896 // Creating a new session cookie based on the newly created session if (session != null && getContext() != null) { @@ -3126,10 +2893,9 @@ protected Session doGetSession(boolean create) { if (session != null) { session.access(); return session; - } else { - return null; } + return null; } /** @@ -3141,25 +2907,19 @@ protected void configureSessionCookie(Cookie cookie) { cookie.setHttpOnly(true); cookie.setMaxAge(-1); String contextPath = null; - // START GlassFish 1024 if (isDefaultContext) { cookie.setPath("/"); } else { - // END GlassFish 1024 if (context != null) { - // START OF SJSAS 6231069 - // contextPath = getContext().getEncodedPath(); contextPath = context.getPath(); - // END OF SJSAS 6231069 } if (contextPath != null && contextPath.length() > 0) { cookie.setPath(contextPath); } else { cookie.setPath("/"); } - // START GlassFish 1024 } - // END GlassFish 1024 + if (isSecure()) { cookie.setSecure(true); } @@ -3167,8 +2927,7 @@ protected void configureSessionCookie(Cookie cookie) { // Override the default config with servlet context // sessionCookieConfig if (context != null) { - SessionCookieConfig sessionCookieConfig = - context.getSessionCookieConfig(); + SessionCookieConfig sessionCookieConfig = context.getSessionCookieConfig(); if (sessionCookieConfig.getDomain() != null) { cookie.setDomain(sessionCookieConfig.getDomain()); } @@ -3179,7 +2938,8 @@ protected void configureSessionCookie(Cookie cookie) { cookie.setVersion(1); cookie.setComment(sessionCookieConfig.getComment()); } - // do nothing if it is already secure + + // Do nothing if it is already secure if (!cookie.getSecure()) { cookie.setSecure(sessionCookieConfig.isSecure()); } @@ -3196,7 +2956,6 @@ protected void configureSessionCookie(Cookie cookie) { * Parse cookies. */ protected void parseCookies() { - cookiesParsed = true; org.glassfish.grizzly.http.Cookie[] serverCookies = coyoteRequest.getCookies(); @@ -3210,13 +2969,7 @@ protected void parseCookies() { for (int i = 0; i < count; i++) { org.glassfish.grizzly.http.Cookie scookie = serverCookies[i]; try { - /* GlassFish 898 - Cookie cookie = new Cookie(scookie.getName().toString(), - scookie.getValue().toString()); - */ - // START GlassFish 898 Cookie cookie = makeCookie(scookie); - // END GlassFish 898 cookie.setPath(scookie.getPath()); cookie.setVersion(scookie.getVersion()); String domain = scookie.getDomain(); @@ -3225,18 +2978,16 @@ protected void parseCookies() { } cookies.add(cookie); } catch (IllegalArgumentException e) { - ; // Ignore bad cookie. + // Ignore bad cookie. } } } - // START GlassFish 898 protected Cookie makeCookie(org.glassfish.grizzly.http.Cookie scookie) { return makeCookie(scookie, false); } protected Cookie makeCookie(org.glassfish.grizzly.http.Cookie scookie, boolean decode) { - String name = scookie.getName(); String value = scookie.getValue(); @@ -3252,110 +3003,13 @@ protected Cookie makeCookie(org.glassfish.grizzly.http.Cookie scookie, boolean d return new Cookie(name, value); } - // END GlassFish 898 - - /** - * Parse request parameters. - */ -// protected void parseRequestParameters() { -// -// /* SJSAS 4936855 -// requestParametersParsed = true; -// */ -// -// Parameters parameters = coyoteRequest.getParameters(); -// -// // getCharacterEncoding() may have been overridden to search for -// // hidden form field containing request encoding -// String enc = getCharacterEncoding(); -// // START SJSAS 4936855 -// // Delay updating requestParametersParsed to TRUE until -// // after getCharacterEncoding() has been called, because -// // getCharacterEncoding() may cause setCharacterEncoding() to be -// // called, and the latter will ignore the specified encoding if -// // requestParametersParsed is TRUE -// requestParametersParsed = true; -// // END SJSAS 4936855 -// if (enc != null) { -// parameters.setEncoding(enc); -// parameters.setQueryStringEncoding(enc); -// } else { -// parameters.setEncoding(org.glassfish.grizzly.http.server.Constants.DEFAULT_CHARACTER_ENCODING); -// parameters.setQueryStringEncoding(org.glassfish.grizzly.http.server.Constants.DEFAULT_CHARACTER_ENCODING); -// } -// -// parameters.handleQueryParameters(); -// -// if (usingInputStream || usingReader) { -// return; -// } -// -// if (!"POST".equalsIgnoreCase(getMethod())) { -// return; -// } -// -// String contentType = getContentType(); -// if (contentType == null) { -// contentType = ""; -// } -// int semicolon = contentType.indexOf(';'); -// if (semicolon >= 0) { -// contentType = contentType.substring(0, semicolon).trim(); -// } else { -// contentType = contentType.trim(); -// } -// if (!"application/x-www-form-urlencoded".equals(contentType)) { -// return; -// } -// -// int len = getContentLength(); -// -// if (len > 0) { -// int maxPostSize = ((Connector) connector).getMaxPostSize(); -// if (maxPostSize > 0 && len > maxPostSize) { -// log(sm.getString("coyoteRequest.postTooLarge")); - - //coyoteRequest.postTooLarge=PWC4004: Parameters were not parsed because the size of the posted data was too big. - // Use the maxPostSize attribute of the connector to resolve this if the application should accept large POSTs. -// -// throw new IllegalStateException("Post too large"); -// } -// try { -// /* SJSAS 6346738 -// byte[] formData = null; -// if (len < CACHED_POST_LEN) { -// if (postData == null) -// postData = new byte[CACHED_POST_LEN]; -// formData = postData; -// } else { -// formData = new byte[len]; -// } -// int actualLen = readPostBody(formData, len); -// if (actualLen == len) { -// parameters.processParameters(formData, 0, len); -// } -// */ -// // START SJSAS 6346738 -// byte[] formData = getPostBody(); -// if (formData != null) { -// parameters.processParameters(formData, 0, len); -// } -// // END SJSAS 6346738 -// } catch (Throwable t) { -// ; // Ignore -// } -// } -// -// } - - // START SJSAS 6346738 + /** * Gets the POST body of this request. * * @return The POST body of this request */ protected byte[] getPostBody() throws IOException { - int len = getContentLength(); byte[] formData = null; @@ -3374,158 +3028,23 @@ protected byte[] getPostBody() throws IOException { return null; } - // END SJSAS 6346738 /** * Read post body in an array. */ - protected int readPostBody(byte body[], int len) - throws IOException { - + protected int readPostBody(byte body[], int len) throws IOException { Buffer b = coyoteRequest.getPostBody(len).duplicate(); final int length = b.limit() - b.position(); b.get(body, b.position(), length); return length; - } /** - * Parse request locales. - */ -// protected void parseLocales() { -// -// localesParsed = true; -// for (String value : getHeaders("accept-language")) { -// parseLocalesHeader(value); -// } -// -// } - - /** - * Parse accept-language header value. - */ -// protected void parseLocalesHeader(String value) { -// - // Store the accumulated languages that have been requested in -// // a local collection, sorted by the quality value (so we can -// // add Locales in descending order). The values will be ArrayLists -// // containing the corresponding Locales to be added -// TreeMap> locales = new TreeMap>(); -// -// // Preprocess the value to remove all whitespace -// int white = value.indexOf(' '); -// if (white < 0) { -// white = value.indexOf('\t'); -// } -// if (white >= 0) { -// StringBuilder sb = new StringBuilder(); -// int len = value.length(); -// for (int i = 0; i < len; i++) { -// char ch = value.charAt(i); -// if ((ch != ' ') && (ch != '\t')) { -// sb.append(ch); -// } -// } -// value = sb.toString(); -// } -// -// // Process each comma-delimited language specification -// parser.setString(value); // ASSERT: parser is available to us -// int length = parser.getLength(); -// while (true) { -// -// // Extract the next comma-delimited entry -// int start = parser.getIndex(); -// if (start >= length) { -// break; -// } -// int end = parser.findChar(','); -// String entry = parser.extract(start, end).trim(); -// parser.advance(); // For the following entry -// -// // Extract the quality factor for this entry -// double quality = 1.0; -// int semi = entry.indexOf(";q="); -// if (semi >= 0) { -// try { -// String strQuality = entry.substring(semi + 3); -// if (strQuality.length() <= 5) { -// quality = Double.parseDouble(strQuality); -// } else { -// quality = 0.0; -// } -// } catch (NumberFormatException e) { -// quality = 0.0; -// } -// entry = entry.substring(0, semi); -// } -// -// // Skip entries we are not going to keep track of -// if (quality < 0.00005) { -// continue; // Zero (or effectively zero) quality factors -// } -// if ("*".equals(entry)) { -// continue; // FIXME - "*" entries are not handled -// } -// // Extract the language and country for this entry -// String language = null; -// String country = null; -// String variant = null; -// int dash = entry.indexOf('-'); -// if (dash < 0) { -// language = entry; -// country = ""; -// variant = ""; -// } else { -// language = entry.substring(0, dash); -// country = entry.substring(dash + 1); -// int vDash = country.indexOf('-'); -// if (vDash > 0) { -// String cTemp = country.substring(0, vDash); -// variant = country.substring(vDash + 1); -// country = cTemp; -// } else { -// variant = ""; -// } -// } -// -// if (!isAlpha(language) || !isAlpha(country) || !isAlpha(variant)) { -// continue; -// } -// -// // Add a new Locale to the list of Locales for this quality level -// Locale locale = new Locale(language, country, variant); -// Double key = Double.valueOf(-quality); // Reverse the order -// ArrayList values = locales.get(key); -// if (values == null) { -// values = new ArrayList(); -// locales.put(key, values); -// } -// values.add(locale); -// -// } -// -// // Process the quality values in highest->lowest order (due to -// // negating the Double value when creating the key) -// for (ArrayList list : locales.values()) { -// Iterator values = list.iterator(); -// while (values.hasNext()) { -// Locale locale = values.next(); -// addLocale(locale); -// } -// } -// -// } - - /* - * Returns true if the given string is composed of upper- or lowercase - * letters only, false otherwise. + * Returns true if the given string is composed of upper- or lowercase letters only, false otherwise. * - * @return true if the given string is composed of upper- or lowercase - * letters only, false otherwise. + * @return true if the given string is composed of upper- or lowercase letters only, false otherwise. */ protected static final boolean isAlpha(String value) { - if (value == null) { return false; } @@ -3549,67 +3068,16 @@ protected void obtainSessionId() { setRequestedSessionId(coyoteRequest.getRequestedSessionId()); } - // START CR 6309511 /** * Parse session id in URL. */ protected void parseSessionId(String sessionParameterName, CharChunk uriBB) { - //START GLASSFISH-15508 - /* - if (coyoteRequest.isRequestedSessionIdFromURL() && - sessionParam.equals(Globals.SESSION_PARAMETER_NAME)) { - setRequestedSessionURL(true); - setRequestedSessionId(coyoteRequest.getRequestedSessionId()); - setJrouteId(coyoteRequest.getJrouteId()); - - return; - } - - sessionParam = ";" + sessionParam + "="; - int semicolon = uriBB.indexOf(sessionParam, 0, sessionParam.length(), - 0); - if (semicolon >= 0) { - - // Parse session ID, and extract it from the decoded request URI - int start = uriBB.getStart(); - int end = uriBB.getEnd(); - - int sessionIdStart = start + semicolon + sessionParam.length(); - int semicolon2 = uriBB.indexOf(';', sessionIdStart); - */ - //END GLASSFISH-15508 - /* SJSAS 6346226 - if (semicolon2 >= 0) { - setRequestedSessionId - (new String(uriBB.getBuffer(), sessionIdStart, - semicolon2 - semicolon - match.length())); - } else { - setRequestedSessionId - (new String(uriBB.getBuffer(), sessionIdStart, - end - sessionIdStart)); - } - */ - //START GLASSFISH-15508 - /* - // START SJSAS 6346226 - String sessionId = null; - if (semicolon2 >= 0) { - sessionId = new String(uriBB.getBuffer(), sessionIdStart, - semicolon2 - semicolon - sessionParam.length()); - } else { - sessionId = new String(uriBB.getBuffer(), sessionIdStart, - end - sessionIdStart); - } - */ - //END GLASSFISH-15508 // Parse session ID, and extract it from the decoded request URI String sessionParam = ";" + sessionParameterName + "="; - String sessionId = - parseParameterFromRequestURI(uriBB, sessionParam); + String sessionId = parseParameterFromRequestURI(uriBB, sessionParam); if (sessionId != null) { - // START SJSAS 6346226 int jrouteIndex = sessionId.lastIndexOf(':'); if (jrouteIndex > 0) { setRequestedSessionId(sessionId.substring(0, jrouteIndex)); @@ -3619,65 +3087,33 @@ protected void parseSessionId(String sessionParameterName, CharChunk uriBB) { } else { setRequestedSessionId(sessionId); } - // END SJSAS 6346226 setRequestedSessionURL(true); - /* SJSWS 6376484 - // Extract session ID from request URI - ByteChunk uriBC = coyoteRequest.requestURI().getByteChunk(); - start = uriBC.getStart(); - end = uriBC.getEnd(); - semicolon = uriBC.indexOf(match, 0, match.length(), 0); - - if (semicolon > 0) { - sessionIdStart = start + semicolon; - semicolon2 = uriBB.indexOf - (';', start + semicolon + match.length()); - uriBC.setEnd(start + semicolon); - byte[] buf = uriBC.getBuffer(); - if (semicolon2 >= 0) { - for (int i = 0; i < end - start - semicolon2; i++) { - buf[start + semicolon + i] - = buf[start + i + semicolon2]; - } - uriBC.setBytes(buf, start, semicolon - + (end - start - semicolon2)); - } - } - */ - // START SJSWS 6376484 /* - * Parse the session id from the encoded URI only if the encoded - * URI is not null, to allow for lazy evaluation + * Parse the session id from the encoded URI only if the encoded URI is not null, to allow for lazy evaluation */ if (coyoteRequest.getRequestURI() != null) { removeParameterFromRequestURI(sessionParam); } - // END SJSWS 6376484 } else { setRequestedSessionId(null); setRequestedSessionURL(false); } } - // END CR 6309511 /** - * Parses and removes any session version (if present) from the request - * URI. + * Parses and removes any session version (if present) from the request URI. * */ protected void parseSessionVersion(CharChunk uriCC) { - String sessionVersionString = - parseParameterFromRequestURI(uriCC, Globals.SESSION_VERSION_PARAMETER); + String sessionVersionString = parseParameterFromRequestURI(uriCC, SESSION_VERSION_PARAMETER); if (sessionVersionString != null) { parseSessionVersionString(sessionVersionString); -// if (!coyoteRequest.requestURI().getByteChunk().isNull()) { - removeParameterFromRequestURI(Globals.SESSION_VERSION_PARAMETER); -// } + removeParameterFromRequestURI(SESSION_VERSION_PARAMETER); } } @@ -3685,17 +3121,14 @@ protected void parseSessionVersion(CharChunk uriCC) { * Parses and removes jreplica (if present) from the request URI. */ protected void parseJReplica(CharChunk uriCC) { - String jreplica = - parseParameterFromRequestURI(uriCC, Globals.JREPLICA_PARAMETER); + String jreplica = parseParameterFromRequestURI(uriCC, JREPLICA_PARAMETER); if (jreplica != null) { Session session = getSessionInternal(false); if (session != null) { - session.setNote(Globals.JREPLICA_SESSION_NOTE, jreplica); + session.setNote(JREPLICA_SESSION_NOTE, jreplica); } -// if (!coyoteRequest.requestURI().getByteChunk().isNull()) { - removeParameterFromRequestURI(Globals.JREPLICA_PARAMETER); -// } + removeParameterFromRequestURI(JREPLICA_PARAMETER); } } @@ -3704,27 +3137,23 @@ private void addSessionCookie() { if (context != null && context.getCookies() && response != null) { String jvmRoute = ((StandardContext) getContext()).getJvmRoute(); /* - * Check if context has been configured with jvmRoute for - * Apache LB. If it has, do not add the JSESSIONID cookie - * here, but rely on OutputBuffer#addSessionCookieWithJvmRoute - * to add the jvmRoute enhanced JSESSIONID as a cookie right + * Check if context has been configured with jvmRoute for Apache LB. If it has, do not add the JSESSIONID cookie here, + * but rely on OutputBuffer#addSessionCookieWithJvmRoute to add the jvmRoute enhanced JSESSIONID as a cookie right * before the response is flushed. */ if (jvmRoute == null) { - Cookie newCookie = new Cookie( - getSafeHeaderValue(getContext().getSessionCookieName()), getSafeHeaderValue(session.getId())); + Cookie newCookie = new Cookie(getSafeHeaderValue(getContext().getSessionCookieName()), getSafeHeaderValue(session.getId())); configureSessionCookie(newCookie); - ((HttpResponse)response).addSessionCookieInternal(newCookie); + ((HttpResponse) response).addSessionCookieInternal(newCookie); } } } /** - * @param parameter of the form ";" + parameterName + "=" + * @param parameter of the form ";" + parameterName + "=" * @return parameterValue */ private String parseParameterFromRequestURI(CharChunk uriCC, String parameter) { - String parameterValue = null; int semicolon = uriCC.indexOf(parameter, 0, parameter.length(), 0); @@ -3736,15 +3165,9 @@ private String parseParameterFromRequestURI(CharChunk uriCC, String parameter) { int parameterStart = start + semicolon + parameter.length(); int semicolon2 = uriCC.indexOf(';', semicolon + parameter.length()); if (semicolon2 >= 0) { - parameterValue = new String( - uriCC.getBuffer(), - parameterStart, - semicolon2 - semicolon - parameter.length()); + parameterValue = new String(uriCC.getBuffer(), parameterStart, semicolon2 - semicolon - parameter.length()); } else { - parameterValue = new String( - uriCC.getBuffer(), - parameterStart, - end - parameterStart); + parameterValue = new String(uriCC.getBuffer(), parameterStart, end - parameterStart); } } @@ -3752,20 +3175,16 @@ private String parseParameterFromRequestURI(CharChunk uriCC, String parameter) { return parameterValue; } - // START SJSWS 6376484 /** * Removes the session version from the request URI. - * @param parameter of the form ";" + parameterName + "=" + * + * @param parameter of the form ";" + parameterName + "=" */ private void removeParameterFromRequestURI(String parameter) { - int semicolon, semicolon2; - final DataChunk uriBC = - coyoteRequest.getRequest().getRequestURIRef().getRequestURIBC(); + final DataChunk uriBC = coyoteRequest.getRequest().getRequestURIRef().getRequestURIBC(); -// start = uriBC.getStart(); -// end = uriBC.getEnd(); semicolon = uriBC.indexOf(parameter, 0); if (semicolon > 0) { @@ -3780,39 +3199,24 @@ private void removeParameterFromRequestURI(String parameter) { } uriBC.delete(semicolon, end); -// uriBC.setEnd(start + semicolon); -// byte[] buf = uriBC.getBuffer(); -// if (semicolon2 >= 0) { -// for (int i = 0; i < end - start - semicolon2; i++) { -// buf[start + semicolon + i] = buf[start + i + semicolon2]; -// } -// uriBC.setBytes(buf, start, semicolon -// + (end - start - semicolon2)); -// } } } - // END SJSWS 6376484 /* - * Parses the given session version string into its components. Each - * component is stored as an entry in a HashMap, which maps a context - * path to its session version number. The HashMap is stored as a - * request attribute, to make it available to any target contexts to which - * this request may be dispatched. + * Parses the given session version string into its components. Each component is stored as an entry in a HashMap, which + * maps a context path to its session version number. The HashMap is stored as a request attribute, to make it available + * to any target contexts to which this request may be dispatched. * - * This method also sets the session version number for the context with - * which this request has been associated. + * This method also sets the session version number for the context with which this request has been associated. */ void parseSessionVersionString(String sessionVersionString) { if (sessionVersionString == null || !isSessionVersioningSupported()) { return; } - HashMap sessionVersions = - RequestUtil.parseSessionVersionString(sessionVersionString); + HashMap sessionVersions = RequestUtil.parseSessionVersionString(sessionVersionString); if (sessionVersions != null) { - attributes.put(Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE, - sessionVersions); + attributes.put(SESSION_VERSIONS_REQUEST_ATTRIBUTE, sessionVersions); if (context != null) { String path = context.getPath(); if ("".equals(path)) { @@ -3835,7 +3239,7 @@ void parseJrouteCookie() { for (int i = 0; i < count; i++) { org.glassfish.grizzly.http.Cookie scookie = serverCookies[i]; - if (scookie.getName().equals(Constants.JROUTE_COOKIE)) { + if (scookie.getName().equals(JROUTE_COOKIE)) { setJrouteId(scookie.getValue()); break; } @@ -3852,20 +3256,16 @@ void setJrouteId(String jrouteId) { } /** - * Gets the jroute id of this request, which may have been - * sent as a separate JROUTE cookie or appended to the - * session identifier encoded in the URI (if cookies have been disabled). + * Gets the jroute id of this request, which may have been sent as a separate JROUTE cookie or appended to + * the session identifier encoded in the URI (if cookies have been disabled). * - * @return The jroute id of this request, or null if this request does not - * carry any jroute id + * @return The jroute id of this request, or null if this request does not carry any jroute id */ @Override public String getJrouteId() { return jrouteId; } - // END SJSAS 6346226 - // START CR 6309511 /** * Parse session id in URL. */ @@ -3887,10 +3287,11 @@ protected void parseSessionCookiesId() { return; } - String sessionCookieName = Globals.SESSION_COOKIE_NAME; + String sessionCookieName = SESSION_COOKIE_NAME; if (context != null) { sessionCookieName = context.getSessionCookieName(); } + for (int i = 0; i < count; i++) { org.glassfish.grizzly.http.Cookie scookie = serverCookies[i]; if (scookie.getName().equals(sessionCookieName)) { @@ -3913,22 +3314,18 @@ protected void parseSessionCookiesId() { setRequestedSessionId(scookie.getValue()); // TODO: Pass cookie path into // getSessionVersionFromCookie() - String sessionVersionString = - getSessionVersionFromCookie(); + String sessionVersionString = getSessionVersionFromCookie(); parseSessionVersionString(sessionVersionString); } } } } } - // END CR 6309511 /* - * Returns the value of the first JSESSIONIDVERSION cookie, or null - * if no such cookie present in the request. + * Returns the value of the first JSESSIONIDVERSION cookie, or null if no such cookie present in the request. * - * TODO: Add cookie path argument, and return value of JSESSIONIDVERSION - * cookie with the specified path. + * TODO: Add cookie path argument, and return value of JSESSIONIDVERSION cookie with the specified path. */ private String getSessionVersionFromCookie() { if (!isSessionVersioningSupported()) { @@ -3943,8 +3340,7 @@ private String getSessionVersionFromCookie() { for (int i = 0; i < count; i++) { org.glassfish.grizzly.http.Cookie scookie = serverCookies[i]; - if (scookie.getName().equals( - Globals.SESSION_VERSION_COOKIE_NAME)) { + if (scookie.getName().equals(SESSION_VERSION_COOKIE_NAME)) { return scookie.getValue(); } } @@ -3959,12 +3355,10 @@ CharChunk getURIParams() { return uriParamsCC; } - // START CR 6309511 /** * Character conversion of the URI. */ - protected void convertURI(MessageBytes uri) - throws Exception { + protected void convertURI(MessageBytes uri) throws Exception { ByteChunk bc = uri.getByteChunk(); CharChunk cc = uri.getCharChunk(); @@ -3972,8 +3366,7 @@ protected void convertURI(MessageBytes uri) cc.allocate(length, -1); String enc = connector.getURIEncoding(); - if (enc != null && !enc.isEmpty() && - !Globals.ISO_8859_1_ENCODING.equalsIgnoreCase(enc)) { + if (enc != null && !enc.isEmpty() && !ISO_8859_1_ENCODING.equalsIgnoreCase(enc)) { B2CConverter conv = getURIConverter(); try { if (conv == null) { @@ -3982,17 +3375,16 @@ protected void convertURI(MessageBytes uri) } } catch (IOException e) { // Ignore - log.log(Level.SEVERE, LogFacade.INVALID_URI_ENCODING); + log.log(SEVERE, INVALID_URI_ENCODING); connector.setURIEncoding(null); } if (conv != null) { try { conv.convert(bc, cc, cc.getBuffer().length - cc.getEnd()); - uri.setChars(cc.getBuffer(), cc.getStart(), - cc.getLength()); + uri.setChars(cc.getBuffer(), cc.getStart(), cc.getLength()); return; } catch (IOException e) { - log.log(Level.SEVERE, LogFacade.INVALID_URI_CHAR_ENCODING); + log.log(SEVERE, INVALID_URI_CHAR_ENCODING); cc.recycle(); } } @@ -4008,14 +3400,12 @@ protected void convertURI(MessageBytes uri) uri.setChars(cbuf, 0, length); } - // END CR 6309511 @Override public DispatcherType getDispatcherType() { - DispatcherType dispatcher = (DispatcherType) getAttribute( - Globals.DISPATCHER_TYPE_ATTR); + DispatcherType dispatcher = (DispatcherType) getAttribute(DISPATCHER_TYPE_ATTR); if (dispatcher == null) { - dispatcher = DispatcherType.REQUEST; + dispatcher = REQUEST; } return dispatcher; } @@ -4031,31 +3421,22 @@ public AsyncContext startAsync() throws IllegalStateException { /** * Starts async processing on this request. * - * @param servletRequest the ServletRequest with which to initialize - * the AsyncContext - * @param servletResponse the ServletResponse with which to initialize - * the AsyncContext + * @param servletRequest the ServletRequest with which to initialize the AsyncContext + * @param servletResponse the ServletResponse with which to initialize the AsyncContext */ @Override - public AsyncContext startAsync(ServletRequest servletRequest, - ServletResponse servletResponse) - throws IllegalStateException { + public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return startAsync(servletRequest, servletResponse, false); } /** * Starts async processing on this request. * - * @param servletRequest the ServletRequest with which to initialize - * the AsyncContext - * @param servletResponse the ServletResponse with which to initialize - * the AsyncContext - * @param isStartAsyncWithZeroArg true if the zero-arg version of - * startAsync was called, false otherwise - */ - private AsyncContext startAsync(ServletRequest servletRequest, - ServletResponse servletResponse, - boolean isStartAsyncWithZeroArg) + * @param servletRequest the ServletRequest with which to initialize the AsyncContext + * @param servletResponse the ServletResponse with which to initialize the AsyncContext + * @param isStartAsyncWithZeroArg true if the zero-arg version of startAsync was called, false otherwise + */ + private AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse, boolean isStartAsyncWithZeroArg) throws IllegalStateException { if (servletRequest == null || servletResponse == null) { @@ -4063,44 +3444,36 @@ private AsyncContext startAsync(ServletRequest servletRequest, } if (!isAsyncSupported()) { - throw new IllegalStateException(rb.getString(LogFacade.REQUEST_WITHIN_SCOPE_OF_FILTER_OR_SERVLET_EXCEPTION)); + throw new IllegalStateException(rb.getString(REQUEST_WITHIN_SCOPE_OF_FILTER_OR_SERVLET_EXCEPTION)); } final AsyncContextImpl asyncContextLocal = asyncContext; if (asyncContextLocal != null) { if (isAsyncStarted()) { - throw new IllegalStateException(rb.getString(LogFacade.START_ASYNC_CALLED_AGAIN_EXCEPTION)); + throw new IllegalStateException(rb.getString(START_ASYNC_CALLED_AGAIN_EXCEPTION)); } if (asyncContextLocal.isAsyncComplete()) { - throw new IllegalStateException(rb.getString(LogFacade.ASYNC_ALREADY_COMPLETE_EXCEPTION)); + throw new IllegalStateException(rb.getString(ASYNC_ALREADY_COMPLETE_EXCEPTION)); } if (!asyncContextLocal.isStartAsyncInScope()) { - throw new IllegalStateException(rb.getString(LogFacade.START_ASYNC_CALLED_OUTSIDE_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(START_ASYNC_CALLED_OUTSIDE_SCOPE_EXCEPTION)); } // Reinitialize existing AsyncContext - asyncContextLocal.reinitialize(servletRequest, servletResponse, - isStartAsyncWithZeroArg); + asyncContextLocal.reinitialize(servletRequest, servletResponse, isStartAsyncWithZeroArg); } else { final AsyncContextImpl asyncContextFinal = - new AsyncContextImpl(this, - servletRequest, - (Response) getResponse(), - servletResponse, - isStartAsyncWithZeroArg); + new AsyncContextImpl(this, servletRequest, (Response) getResponse(), servletResponse, isStartAsyncWithZeroArg); asyncContext = asyncContextFinal; - final CompletionHandler requestCompletionHandler = - new EmptyCompletionHandler() { + final CompletionHandler requestCompletionHandler = new EmptyCompletionHandler<>() { - @Override - public void completed(org.glassfish.grizzly.http.server.Response response) { - asyncContextFinal.notifyAsyncListeners( - AsyncContextImpl.AsyncEventType.COMPLETE, - null); - } - }; + @Override + public void completed(org.glassfish.grizzly.http.server.Response response) { + asyncContextFinal.notifyAsyncListeners(AsyncContextImpl.AsyncEventType.COMPLETE, null); + } + }; final TimeoutHandler timeoutHandler = new TimeoutHandler() { @@ -4110,8 +3483,7 @@ public boolean onTimeout(final org.glassfish.grizzly.http.server.Response respon } }; - coyoteRequest.getResponse().suspend(-1, TimeUnit.MILLISECONDS, - requestCompletionHandler, timeoutHandler); + coyoteRequest.getResponse().suspend(-1, TimeUnit.MILLISECONDS, requestCompletionHandler, timeoutHandler); asyncStartedThread = Thread.currentThread(); } @@ -4135,9 +3507,8 @@ void setAsyncStarted(boolean asyncStarted) { /** * Disables async support for this request. * - * Async support is disabled as soon as this request has passed a filter - * or servlet that does not support async (either via the designated - * annotation or declaratively). + * Async support is disabled as soon as this request has passed a filter or servlet that does not support async (either + * via the designated annotation or declaratively). */ @Override public void disableAsyncSupport() { @@ -4145,8 +3516,8 @@ public void disableAsyncSupport() { } void setAsyncTimeout(long timeout) { - coyoteRequest.getResponse().getSuspendContext().setTimeout( - timeout, TimeUnit.MILLISECONDS);; + coyoteRequest.getResponse().getSuspendContext().setTimeout(timeout, TimeUnit.MILLISECONDS); + } /** @@ -4163,29 +3534,26 @@ public boolean isAsyncSupported() { @Override public AsyncContext getAsyncContext() { if (!isAsyncStarted()) { - throw new IllegalStateException(rb.getString(LogFacade.REQUEST_NOT_PUT_INTO_ASYNC_MODE_EXCEPTION)); + throw new IllegalStateException(rb.getString(REQUEST_NOT_PUT_INTO_ASYNC_MODE_EXCEPTION)); } return asyncContext; } /* - * Invokes any registered AsyncListener instances at their - * onComplete method + * Invokes any registered AsyncListener instances at their onComplete method */ void asyncComplete() { asyncStarted.set(false); - if (asyncStartedThread != Thread.currentThread() || - !asyncContext.isOkToConfigure()) { + if (asyncStartedThread != Thread.currentThread() || !asyncContext.isOkToConfigure()) { // it's not safe to just mark response as resumed coyoteRequest.getResponse().resume(); } else { // This code is called if we startAsync and complete in the service() thread. // So instead of resuming the suspendedContext (which will finish the response processing), // we just have to mark the context as resumed like it has never been suspended. - final SuspendedContextImpl suspendContext = - (SuspendedContextImpl) coyoteRequest.getResponse().getSuspendContext(); + final SuspendedContextImpl suspendContext = (SuspendedContextImpl) coyoteRequest.getResponse().getSuspendContext(); suspendContext.markResumed(); suspendContext.getSuspendStatus().reset(); @@ -4193,41 +3561,36 @@ void asyncComplete() { } /* - * Invokes all registered AsyncListener instances at their - * onTimeout method. + * Invokes all registered AsyncListener instances at their onTimeout method. * - * This method also performs an error dispatch and completes the response - * if none of the listeners have done so. + * This method also performs an error dispatch and completes the response if none of the listeners have done so. */ void asyncTimeout() { if (asyncContext != null) { - asyncContext.notifyAsyncListeners( - AsyncContextImpl.AsyncEventType.TIMEOUT, null); + asyncContext.notifyAsyncListeners(AsyncContextImpl.AsyncEventType.TIMEOUT, null); } inputBuffer.disableReadHandler(); if (response instanceof Response) { - ((Response)response).disableWriteHandler(); + ((Response) response).disableWriteHandler(); } errorDispatchAndComplete(null); } /** - * Notifies this Request that the container-initiated dispatch - * during which ServletRequest#startAsync was called is about to - * return to the container + * Notifies this Request that the container-initiated dispatch during which ServletRequest#startAsync was called is + * about to return to the container */ void onExitService() { - final AsyncContextImpl ac = asyncContext; + final AsyncContextImpl asyncContextImpl = asyncContext; - if (ac != null) { - ac.setOkToConfigure(false); + if (asyncContextImpl != null) { + asyncContextImpl.setOkToConfigure(false); if (asyncStarted.get()) { - coyoteRequest.getResponse().getSuspendContext().setTimeout( - ac.getTimeout(), TimeUnit.MILLISECONDS); + coyoteRequest.getResponse().getSuspendContext().setTimeout(asyncContextImpl.getTimeout(), TimeUnit.MILLISECONDS); } - ac.onExitService(); + asyncContextImpl.onExitService(); } afterService = true; if (resume) { @@ -4258,35 +3621,29 @@ private boolean processTimeout() { void errorDispatchAndComplete(Throwable t) { /* - * If no listeners, or none of the listeners called - * AsyncContext#complete or any of the AsyncContext#dispatch - * methods (in which case asyncStarted would have been set to false), - * perform an error dispatch with a status code equal to 500. + * If no listeners, or none of the listeners called AsyncContext#complete or any of the AsyncContext#dispatch methods + * (in which case asyncStarted would have been set to false), perform an error dispatch with a status code equal to 500. */ - final AsyncContextImpl ac = asyncContext; - if (ac != null - && !ac.isDispatchInScope() - && !ac.isAsyncComplete()) { - ((HttpServletResponse) response).setStatus( - HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + final AsyncContextImpl asyncContextImpl = asyncContext; + if (asyncContextImpl != null && !asyncContextImpl.isDispatchInScope() && !asyncContextImpl.isAsyncComplete()) { + ((HttpServletResponse) response).setStatus(SC_INTERNAL_SERVER_ERROR); response.setError(); if (t != null) { - setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); + setAttribute(ERROR_EXCEPTION, t); } try { if (hostValve != null) { hostValve.postInvoke(this, response); } } catch (Exception e) { - log.log(Level.SEVERE, LogFacade.UNABLE_PERFORM_ERROR_DISPATCH, e); + log.log(SEVERE, UNABLE_PERFORM_ERROR_DISPATCH, e); } finally { /* - * If no matching error page was found, or the error page - * did not call AsyncContext#complete or any of the + * If no matching error page was found, or the error page did not call AsyncContext#complete or any of the * AsyncContext#dispatch methods, call AsyncContext#complete */ - if (!ac.isAsyncComplete()) { - ac.complete(); + if (!asyncContextImpl.isAsyncComplete()) { + asyncContextImpl.complete(); } } } @@ -4294,25 +3651,26 @@ void errorDispatchAndComplete(Throwable t) { private Multipart getMultipart() { if (multipart == null) { - multipart = new Multipart(this, - wrapper.getMultipartLocation(), - wrapper.getMultipartMaxFileSize(), - wrapper.getMultipartMaxRequestSize(), - wrapper.getMultipartFileSizeThreshold()); + multipart = + new Multipart( + this, wrapper.getMultipartLocation(), wrapper.getMultipartMaxFileSize(), + wrapper.getMultipartMaxRequestSize(), wrapper.getMultipartFileSizeThreshold()); } + return multipart; } private boolean isMultipartConfigured() { if (wrapper instanceof StandardWrapper) { - return ((StandardWrapper)wrapper).isMultipartConfigured(); + return ((StandardWrapper) wrapper).isMultipartConfigured(); } + return false; } private void checkMultipartConfiguration(String name) { - if (! isMultipartConfigured()) { - String msg = MessageFormat.format(rb.getString(LogFacade.REQUEST_CALLED_WITHOUT_MULTIPART_CONFIG_EXCEPTION), name); + if (!isMultipartConfigured()) { + String msg = MessageFormat.format(rb.getString(REQUEST_CALLED_WITHOUT_MULTIPART_CONFIG_EXCEPTION), name); throw new IllegalStateException(msg); } } @@ -4329,26 +3687,6 @@ public Part getPart(String name) throws IOException, ServletException { return getMultipart().getPart(name); } - /** - * Log a message on the Logger associated with our Container (if any). - * - * @param message Message to be logged - * - private void log(String message) { - org.apache.catalina.Logger logger = null; - if (connector != null && connector.getContainer() != null) { - logger = connector.getContainer().getLogger(); - } - String localName = "Request"; - if (logger != null) { - logger.log(localName + " " + message); - } else { - if (log.isLoggable(Level.INFO)) { - log.info(localName + " " + message); - } - } - }*/ - /** * Log a message on the Logger associated with our Container (if any). * @@ -4360,94 +3698,88 @@ private void log(String message, Throwable t) { if (connector != null && connector.getContainer() != null) { logger = connector.getContainer().getLogger(); } + String localName = "Request"; if (logger != null) { - logger.log(localName + " " + message, t, - org.apache.catalina.Logger.WARNING); + logger.log(localName + " " + message, t, org.apache.catalina.Logger.WARNING); } else { - log.log(Level.WARNING, localName + " " + message, t); + log.log(WARNING, localName + " " + message, t); } } - // START SJSAS 6419950 private void populateSSLAttributes() { RequestUtils.populateSSLAttributes(coyoteRequest); - Object attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR); + Object attr = coyoteRequest.getAttribute(CERTIFICATES_ATTR); if (attr != null) { - attributes.put(Globals.CERTIFICATES_ATTR, attr); + attributes.put(CERTIFICATES_ATTR, attr); } - attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR); + attr = coyoteRequest.getAttribute(CIPHER_SUITE_ATTR); if (attr != null) { - attributes.put(Globals.CIPHER_SUITE_ATTR, attr); + attributes.put(CIPHER_SUITE_ATTR, attr); } - attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR); + attr = coyoteRequest.getAttribute(KEY_SIZE_ATTR); if (attr != null) { - attributes.put(Globals.KEY_SIZE_ATTR, attr); + attributes.put(KEY_SIZE_ATTR, attr); } - attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR); + attr = coyoteRequest.getAttribute(SSL_SESSION_ID_ATTR); if (attr != null) { - attributes.put(Globals.SSL_SESSION_ID_ATTR, attr); + attributes.put(SSL_SESSION_ID_ATTR, attr); } } - // END SJSAS 6419950 - // START GlassFish 896 private void initSessionTracker() { notes.put(Globals.SESSION_TRACKER, sessionTracker); } - // END GlassFish 896 /** - * lock the session associated with this request - * this will be a foreground lock - * checks for background lock to clear - * and does a decay poll loop to wait until - * it is clear; after 5 times it takes control for - * the foreground + * lock the session associated with this request this will be a foreground lock checks for background lock to clear and + * does a decay poll loop to wait until it is clear; after 5 times it takes control for the foreground * * @return the session that's been locked */ @Override public Session lockSession() { - Session sess = getSessionInternal(false); + Session session = getSessionInternal(false); + // Now lock the session - if (sess != null) { + if (session != null) { long pollTime = 200L; int maxNumberOfRetries = 7; int tryNumber = 0; boolean keepTrying = true; boolean lockResult = false; + // Try to lock up to maxNumberOfRetries times. // Poll and wait starting with 200 ms. - while(keepTrying) { - lockResult = sess.lockForeground(); - if(lockResult) { + while (keepTrying) { + lockResult = session.lockForeground(); + if (lockResult) { keepTrying = false; break; } tryNumber++; - if(tryNumber < maxNumberOfRetries) { + if (tryNumber < maxNumberOfRetries) { pollTime = pollTime * 2L; threadSleep(pollTime); } else { // Tried to wait and lock maxNumberOfRetries times. // Unlock the background so we can take over. - log.log(Level.WARNING, LogFacade.BREAKING_BACKGROUND_LOCK_EXCEPTION, sess); - if (sess instanceof StandardSession) { - ((StandardSession)sess).unlockBackground(); + log.log(WARNING, BREAKING_BACKGROUND_LOCK_EXCEPTION, session); + if (session instanceof StandardSession) { + ((StandardSession) session).unlockBackground(); } } } } - return sess; + return session; } private void threadSleep(long sleepTime) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { - ; + } } @@ -4456,48 +3788,45 @@ private void threadSleep(long sleepTime) { */ @Override public void unlockSession() { - Session sess = getSessionInternal(false); + Session session = getSessionInternal(false); // Now unlock the session - if (sess != null) { - sess.unlockForeground(); + if (session != null) { + session.unlockForeground(); } } /** - * Increments the version of the given session, and stores it as a - * request attribute, so it can later be included in a response cookie. + * Increments the version of the given session, and stores it as a request attribute, so it can later be included in a + * response cookie. */ - private void incrementSessionVersion(StandardSession ss, - Context context) { - if (ss == null || context == null) { + private void incrementSessionVersion(StandardSession standardSession, Context context) { + if (standardSession == null || context == null) { return; } - String versionString = Long.toString(ss.incrementVersion()); + String versionString = Long.toString(standardSession.incrementVersion()); Map sessionVersions = getSessionVersionsRequestAttribute(); if (sessionVersions == null) { - sessionVersions = new HashMap(); - setAttribute(Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE, - sessionVersions); + sessionVersions = new HashMap<>(); + setAttribute(SESSION_VERSIONS_REQUEST_ATTRIBUTE, sessionVersions); } + String path = context.getPath(); if ("".equals(path)) { path = "/"; } + sessionVersions.put(path, versionString); } @SuppressWarnings("unchecked") Map getSessionVersionsRequestAttribute() { - return (Map) getAttribute( - Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE); + return (Map) getAttribute(SESSION_VERSIONS_REQUEST_ATTRIBUTE); } private boolean isSessionVersioningSupported() { - return context != null && - context.getManager() != null && - context.getManager().isSessionVersioningSupported(); + return context != null && context.getManager() != null && context.getManager().isSessionVersioningSupported(); } @Override @@ -4518,87 +3847,4 @@ public ServletConnection getServletConnection() { return null; } - /** - * This class will be invoked by Grizzly when a suspended operation is - * resumed {@link org.glassfish.grizzly.http.server.Response#resume} or has timed out. - * See {@link org.glassfish.grizzly.http.server.Response.ResponseAttachment} for details. - */ -// private final static class RequestAttachment extends -// org.glassfish.grizzly.http.server.Response.ResponseAttachment { -// -// private Response res; -// -// public RequestAttachment(Long timeout, A attachment, -// CompletionHandler completionHandler, -// Response res) { -// super(timeout, attachment, completionHandler, res.getCoyoteResponse()); -// this.res = res; -// } -// -// @Override -// public void resume() { -// getCompletionHandler().resumed(getAttachment()); -// if (log.isLoggable(Level.FINE)) { -// log.log(Level.FINE, "RequestAttachement.resume: " + res); -// } -// completeProcessing(); -// } -// -// /** -// * {@inheritDoc} -// */ -// //@Override -// public void handleSelectedKey(SelectionKey selectionKey) { -// if (!selectionKey.isValid() || discardDisconnectEvent){ -// selectionKey.cancel(); -// return; -// } -// try { -// ((Request)getAttachment()).clientClosedConnection = ((SocketChannel)selectionKey.channel()). -// read(ByteBuffer.allocate(1)) == -1; -// } catch (IOException ex) { -// -// } finally{ -// if (((Request)getAttachment()).clientClosedConnection){ -// selectionKey.cancel(); -// getCompletionHandler().cancelled(getAttachment()); -// } -// } -// } -// -// void completeProcessing() { -// try { -// res.finishResponse(); -// } catch (IOException ex) { -// if (log.isLoggable(Level.FINE)) { -// log.log(Level.FINE, "res.finishResponse()" + res); -// } -// } -// res.recycle(); -// res.getRequest().recycle(); -// } -// -// @Override -// public boolean timeout() { -// // If the buffers are empty, commit the response header -// boolean result = true; -// -// try { -// if (log.isLoggable(Level.FINE)) { -// log.log(Level.FINE, "RequestAttachement.timeout: " + res); -// } -// cancel(); -// } finally { -// Request req = (Request)getAttachment(); -// final AsyncContextImpl asyncContext = req.asyncContext; -// if (asyncContext != null && !asyncContext.getAndResetDispatchInScope()) { -// completeProcessing(); -// } else { -// result = false; -// } -// } -// -// return result; -// } -//} } From 7c1b515fcfbe5516cbc91dd1df5d91d27ce14944 Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Thu, 7 Apr 2022 23:58:47 +0200 Subject: [PATCH 06/11] Revert #22079. The initial behaviour was correct after all. Signed-off-by: Arjan Tijms --- .../org/apache/catalina/core/ApplicationDispatcher.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java index 2ab36a71c14..cff441a383a 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationDispatcher.java @@ -1036,12 +1036,6 @@ private ServletRequest wrapRequest(State state) { } //END OF github/javaee/glassfish/issues/21846 - //START OF github/javaee/glassfish/issues/22079 - if (DispatcherType.ASYNC.equals(state.dispatcherType)) { - this.mappingForDispatch = hcurrent.getHttpServletMapping(); - } - //END OF github/javaee/glassfish/issues/22079 - wrapper = new ApplicationHttpRequest (hcurrent, context, crossContext, mappingForDispatch, state.dispatcherType); } else { From 07840216de8e3bd854904c3890b3242d97b474f6 Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Fri, 8 Apr 2022 12:31:18 +0200 Subject: [PATCH 07/11] Refactoring Signed-off-by: Arjan Tijms --- appserver/featuresets/debug/pom.xml | 21 + .../catalina/connector/CoyoteAdapter.java | 692 ++++----- .../apache/catalina/connector/Request.java | 207 ++- .../catalina/core/ApplicationPushBuilder.java | 3 +- .../com/sun/enterprise/web/VirtualServer.java | 1248 +++++++---------- 5 files changed, 928 insertions(+), 1243 deletions(-) diff --git a/appserver/featuresets/debug/pom.xml b/appserver/featuresets/debug/pom.xml index 03e577ac547..fd8c813ab4a 100644 --- a/appserver/featuresets/debug/pom.xml +++ b/appserver/featuresets/debug/pom.xml @@ -62,6 +62,27 @@ org.apache.felix org.apache.felix.framework + + + org.glassfish.grizzly + grizzly-framework + + + org.glassfish.grizzly + grizzly-portunif + + + org.glassfish.grizzly + grizzly-http + + + org.glassfish.grizzly + grizzly-http2 + + + org.glassfish.grizzly + grizzly-http-server + org.glassfish.main.featuresets diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteAdapter.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteAdapter.java index d0b11fd2e34..f02578a59ef 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteAdapter.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteAdapter.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -17,19 +18,30 @@ package org.apache.catalina.connector; +import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static jakarta.servlet.http.HttpServletResponse.SC_NOT_FOUND; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.INFO; +import static java.util.logging.Level.SEVERE; +import static org.apache.catalina.Globals.SESSION_PARAMETER_NAME; +import static org.apache.catalina.LogFacade.FAILED_TO_INITIALIZE_THE_INTERCEPTOR; +import static org.apache.catalina.LogFacade.HTTP_LISTENER_DISABLED; +import static org.apache.catalina.LogFacade.INTERNAL_ERROR; +import static org.apache.catalina.LogFacade.NO_HOST_MATCHES_SERVER_NAME_INFO; +import static org.apache.catalina.LogFacade.PARSING_CLIENT_CERT_EXCEPTION; +import static org.apache.catalina.LogFacade.REQUEST_PROCESSING_EXCEPTION; +import static org.apache.catalina.connector.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER; +import static org.glassfish.internal.api.Globals.getDefaultHabitat; + +import java.io.CharConversionException; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.MessageFormat; import java.util.Collection; import java.util.ResourceBundle; -import java.util.logging.Level; import java.util.logging.Logger; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import com.sun.appserv.ProxyHandler; -import java.io.CharConversionException; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; @@ -37,26 +49,24 @@ import org.apache.catalina.LogFacade; import org.apache.catalina.Wrapper; import org.apache.catalina.core.ContainerBase; -import org.apache.catalina.util.ResponseUtil; import org.apache.catalina.util.ServerInfo; -import org.apache.catalina.util.StringManager; import org.glassfish.common.util.InputValidationUtil; import org.glassfish.grizzly.http.Method; +import org.glassfish.grizzly.http.Note; import org.glassfish.grizzly.http.server.AfterServiceListener; import org.glassfish.grizzly.http.server.HttpHandler; -import org.glassfish.grizzly.http.Note; import org.glassfish.grizzly.http.server.util.MappingData; import org.glassfish.grizzly.http.util.ByteChunk; import org.glassfish.grizzly.http.util.CharChunk; import org.glassfish.grizzly.http.util.DataChunk; import org.glassfish.grizzly.http.util.MessageBytes; -import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.web.valve.GlassFishValve; import org.glassfish.web.valve.ServletContainerInterceptor; +import com.sun.appserv.ProxyHandler; + /** - * Implementation of a request processor which delegates the processing to a - * Coyote processor. + * Implementation of a request processor which delegates the processing to a Coyote processor. * * @author Craig R. McClanahan * @author Remy Maucherat @@ -69,58 +79,50 @@ public class CoyoteAdapter extends HttpHandler { private static final ResourceBundle rb = log.getResourceBundle(); // -------------------------------------------------------------- Constants - private static final String POWERED_BY = "Servlet/3.1 JSP/2.3 " + - "(" + ServerInfo.getServerInfo() + " Java/" + - System.getProperty("java.vm.vendor") + "/" + - System.getProperty("java.specification.version") + ")"; - - -// protected boolean v3Enabled = -// Boolean.valueOf(System.getProperty("v3.grizzly.useMapper", "true")); - - -// public static final int ADAPTER_NOTES = 1; static final String JVM_ROUTE = System.getProperty("jvmRoute"); - private Collection interceptors = null; - protected static final boolean ALLOW_BACKSLASH = Boolean.valueOf(System.getProperty("org.glassfish.grizzly.tcp.tomcat5.CoyoteAdapter.ALLOW_BACKSLASH", "false")); private static final boolean COLLAPSE_ADJACENT_SLASHES = - Boolean.valueOf(System.getProperty( - "com.sun.enterprise.web.collapseAdjacentSlashes", "true")); - - /** - * When mod_jk is used, the adapter must be invoked the same way - * Tomcat does by invoking service(...) and the afterService(...). This - * is a hack to make it compatible with Tomcat 5|6. - */ - private boolean compatWithTomcat = false; - - private String serverName = ServerInfo.getPublicServerInfo(); + Boolean.valueOf(System.getProperty("com.sun.enterprise.web.collapseAdjacentSlashes", "true")); // Make sure this value is always aligned with {@link ContainerMapper} // (@see com.sun.enterprise.v3.service.impl.ContainerMapper) - protected final static Note MAPPING_DATA = - org.glassfish.grizzly.http.server.Request.createNote("MappingData"); - + protected static final Note MAPPING_DATA = + org.glassfish.grizzly.http.server.Request.createNote("MappingData"); static final Note CATALINA_REQUEST_NOTE = - org.glassfish.grizzly.http.server.Request.createNote(Request.class.getName()); + org.glassfish.grizzly.http.server.Request.createNote(Request.class.getName()); static final Note CATALINA_RESPONSE_NOTE = - org.glassfish.grizzly.http.server.Request.createNote(Response.class.getName()); + org.glassfish.grizzly.http.server.Request.createNote(Response.class.getName()); - static final CatalinaAfterServiceListener catalinaAfterServiceListener = - new CatalinaAfterServiceListener(); + static final CatalinaAfterServiceListener catalinaAfterServiceListener = new CatalinaAfterServiceListener(); // Make sure this value is always aligned with {@link ContainerMapper} // (@see com.sun.enterprise.v3.service.impl.ContainerMapper) private final static Note DATA_CHUNK = - org.glassfish.grizzly.http.server.Request.createNote("DataChunk"); + org.glassfish.grizzly.http.server.Request.createNote("DataChunk"); - // ----------------------------------------------------------- Constructors + // ----------------------------------------------------- Instance Variables + private Collection interceptors; + + /** + * When mod_jk is used, the adapter must be invoked the same way Tomcat does by invoking service(...) and the + * afterService(...). This is a hack to make it compatible with Tomcat 5|6. + */ + private boolean compatWithTomcat; + + private String serverName = ServerInfo.getPublicServerInfo(); + + /** + * The CoyoteConnector with which this processor is associated. + */ + private Connector connector; + + + // ----------------------------------------------------------- Constructors /** * Construct a new CoyoteProcessor associated with the specified connector. @@ -134,213 +136,171 @@ public CoyoteAdapter(Connector connector) { } - // ----------------------------------------------------- Instance Variables - - - /** - * The CoyoteConnector with which this processor is associated. - */ - private Connector connector = null; - - // -------------------------------------------------------- Adapter Methods - /** * Service method. */ @Override - public void service(org.glassfish.grizzly.http.server.Request req, - org.glassfish.grizzly.http.server.Response res) - throws Exception { + public void service(org.glassfish.grizzly.http.server.Request grizzlyRequest, org.glassfish.grizzly.http.server.Response grizzlyResponse) throws Exception { + grizzlyResponse.getResponse().setAllowCustomReasonPhrase(USE_CUSTOM_STATUS_MSG_IN_HEADER); - res.getResponse().setAllowCustomReasonPhrase(Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER); - - Request request = req.getNote(CATALINA_REQUEST_NOTE); - Response response = req.getNote(CATALINA_RESPONSE_NOTE); + Request catalinaRequest = grizzlyRequest.getNote(CATALINA_REQUEST_NOTE); + Response catalinaResponse = grizzlyRequest.getNote(CATALINA_RESPONSE_NOTE); // Grizzly already parsed, decoded, and mapped the request. // Let's re-use this info here, before firing the // requestStartEvent probe, so that the mapping data will be // available to any probe event listener via standard // ServletRequest APIs (such as getContextPath()) - MappingData md = req.getNote(MAPPING_DATA); - final boolean v3Enabled = md != null; - if (request == null) { + MappingData mappingData = grizzlyRequest.getNote(MAPPING_DATA); + final boolean v3Enabled = mappingData != null; + if (catalinaRequest == null) { // Create objects - request = (Request) connector.createRequest(); - response = (Response) connector.createResponse(); + catalinaRequest = (Request) connector.createRequest(); + catalinaResponse = (Response) connector.createResponse(); // Link objects - request.setResponse(response); - response.setRequest(request); + catalinaRequest.setResponse(catalinaResponse); + catalinaResponse.setRequest(catalinaRequest); // Set as notes - req.setNote(CATALINA_REQUEST_NOTE, request); - req.setNote(CATALINA_RESPONSE_NOTE, response); -// res.setNote(ADAPTER_NOTES, response); + grizzlyRequest.setNote(CATALINA_REQUEST_NOTE, catalinaRequest); + grizzlyRequest.setNote(CATALINA_RESPONSE_NOTE, catalinaResponse); // Set query string encoding - req.getRequest().getRequestURIRef().setDefaultURIEncoding(Charset.forName(connector.getURIEncoding())); + grizzlyRequest.getRequest().getRequestURIRef().setDefaultURIEncoding(Charset.forName(connector.getURIEncoding())); } - request.setCoyoteRequest(req); - response.setCoyoteResponse(res); + catalinaRequest.setGrizzlyRequest(grizzlyRequest); + catalinaResponse.setCoyoteResponse(grizzlyResponse); if (v3Enabled && !compatWithTomcat) { - request.setMappingData(md); - request.updatePaths(md); + catalinaRequest.setMappingData(mappingData); + catalinaRequest.updatePaths(mappingData); } - req.addAfterServiceListener(catalinaAfterServiceListener); + grizzlyRequest.addAfterServiceListener(catalinaAfterServiceListener); try { - doService(req, request, res, response, v3Enabled); + doService(grizzlyRequest, catalinaRequest, grizzlyResponse, catalinaResponse, v3Enabled); // Request may want to initialize async processing - request.onExitService(); + catalinaRequest.onExitService(); } catch (Throwable t) { - log.log(Level.SEVERE, LogFacade.REQUEST_PROCESSING_EXCEPTION, t); + log.log(SEVERE, REQUEST_PROCESSING_EXCEPTION, t); } } private void enteringServletContainer(Request req, Response res) { - if (interceptors == null) + if (interceptors == null) { return; - for(ServletContainerInterceptor interceptor:interceptors) { - try{ + } + + for (ServletContainerInterceptor interceptor : interceptors) { + try { interceptor.preInvoke(req, res); } catch (Throwable th) { - log.log(Level.SEVERE, LogFacade.INTERNAL_ERROR, th); + log.log(SEVERE, INTERNAL_ERROR, th); } } } private void leavingServletContainer(Request req, Response res) { - if (interceptors == null) + if (interceptors == null) { return; - for(ServletContainerInterceptor interceptor:interceptors) { - try{ + } + + for (ServletContainerInterceptor interceptor : interceptors) { + try { interceptor.postInvoke(req, res); } catch (Throwable th) { - log.log(Level.SEVERE, LogFacade.INTERNAL_ERROR, th); + log.log(SEVERE, INTERNAL_ERROR, th); } } } private void initServletInterceptors() { try { - ServiceLocator services = org.glassfish.internal.api.Globals.getDefaultHabitat(); - interceptors = services.getAllServices(ServletContainerInterceptor.class); + interceptors = getDefaultHabitat().getAllServices(ServletContainerInterceptor.class); } catch (Throwable th) { - log.log(Level.SEVERE, LogFacade.FAILED_TO_INITIALIZE_THE_INTERCEPTOR, th); + log.log(SEVERE, FAILED_TO_INITIALIZE_THE_INTERCEPTOR, th); } } + private void doService( + final org.glassfish.grizzly.http.server.Request grizzlyRequest, final Request catalinaRequest, + final org.glassfish.grizzly.http.server.Response grizzlyResponse, final Response catalinaResponse, final boolean v3Enabled) throws Exception { - private void doService(final org.glassfish.grizzly.http.server.Request req, - final Request request, - final org.glassfish.grizzly.http.server.Response res, - final Response response, - final boolean v3Enabled) - throws Exception { - - // START SJSAS 6331392 // Check connector for disabled state if (!connector.isEnabled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.HTTP_LISTENER_DISABLED), - String.valueOf(connector.getPort())); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, msg); + String msg = MessageFormat.format(rb.getString(HTTP_LISTENER_DISABLED), String.valueOf(connector.getPort())); + if (log.isLoggable(FINE)) { + log.log(FINE, msg); } - response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); + catalinaResponse.sendError(SC_NOT_FOUND, msg); return; } - // END SJSAS 6331392 - -//// "X-Powered-By" header is set by GlassfishHttpCodecFilter -// if (connector.isXpoweredBy()) { -// response.addHeader("X-Powered-By", POWERED_BY); -// } - - // Parse and set Catalina and configuration specific - // request parameters - if ( postParseRequest(req, request, res, response, v3Enabled) ) { + // Parse and set Catalina and configuration specific request parameters + if (postParseRequest(grizzlyRequest, catalinaRequest, grizzlyResponse, catalinaResponse, v3Enabled)) { - // START S1AS 6188932 - boolean authPassthroughEnabled = - connector.getAuthPassthroughEnabled(); + boolean authPassthroughEnabled = connector.getAuthPassthroughEnabled(); ProxyHandler proxyHandler = connector.getProxyHandler(); if (authPassthroughEnabled && proxyHandler != null) { - // START SJSAS 6397218 - if (proxyHandler.getSSLKeysize( - (HttpServletRequest)request.getRequest()) > 0) { - request.setSecure(true); + // Otherwise Servlet request.isSecure() value is not propagated when authPassthroughEnabled is set to true + if (proxyHandler.getSSLKeysize(catalinaRequest.getRequest()) > 0) { + catalinaRequest.setSecure(true); } - // END SJSAS 6397218 X509Certificate[] certs = null; try { - certs = proxyHandler.getSSLClientCertificateChain( - request.getRequest()); + certs = proxyHandler.getSSLClientCertificateChain(catalinaRequest.getRequest()); } catch (CertificateException ce) { - log.log(Level.SEVERE, LogFacade.PARSING_CLIENT_CERT_EXCEPTION, - ce); + log.log(SEVERE, PARSING_CLIENT_CERT_EXCEPTION, ce); } if (certs != null) { - request.setAttribute(Globals.CERTIFICATES_ATTR, - certs); + catalinaRequest.setAttribute(Globals.CERTIFICATES_ATTR, certs); } } - // END S1AS 6188932 - -//// "Server" header is set by GlassfishHttpCodecFilter -// if (serverName != null && !serverName.isEmpty()) { -// response.addHeader("Server", serverName); -// } // Invoke the web container - connector.requestStartEvent(request.getRequest(), - request.getHost(), request.getContext()); + connector.requestStartEvent(catalinaRequest.getRequest(), catalinaRequest.getHost(), catalinaRequest.getContext()); Container container = connector.getContainer(); - enteringServletContainer(request, response); + enteringServletContainer(catalinaRequest, catalinaResponse); try { - request.lockSession(); - if (container.getPipeline().hasNonBasicValves() || - container.hasCustomPipeline()) { - container.getPipeline().invoke(request, response); + catalinaRequest.lockSession(); + if (container.getPipeline().hasNonBasicValves() || container.hasCustomPipeline()) { + container.getPipeline().invoke(catalinaRequest, catalinaResponse); } else { // Invoke host directly - Host host = request.getHost(); + Host host = catalinaRequest.getHost(); if (host == null) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - - String msg = MessageFormat.format(rb.getString(LogFacade.NO_HOST_MATCHES_SERVER_NAME_INFO), - request.getRequest().getServerName()); - response.setDetailMessage(msg); + catalinaResponse.sendError(SC_BAD_REQUEST); + catalinaResponse.setDetailMessage( + MessageFormat.format( + rb.getString(NO_HOST_MATCHES_SERVER_NAME_INFO), + catalinaRequest.getRequest().getServerName())); return; } - if (host.getPipeline().hasNonBasicValves() || - host.hasCustomPipeline()) { - host.getPipeline().invoke(request, response); + + if (host.getPipeline().hasNonBasicValves() || host.hasCustomPipeline()) { + host.getPipeline().invoke(catalinaRequest, catalinaResponse); } else { GlassFishValve hostValve = host.getPipeline().getBasic(); - hostValve.invoke(request, response); + hostValve.invoke(catalinaRequest, catalinaResponse); // Error handling - hostValve.postInvoke(request, response); + hostValve.postInvoke(catalinaRequest, catalinaResponse); } } } finally { try { - connector.requestEndEvent(request.getRequest(), - request.getHost(), request.getContext(), - response.getStatus()); + connector.requestEndEvent(catalinaRequest.getRequest(), catalinaRequest.getHost(), catalinaRequest.getContext(), catalinaResponse.getStatus()); } finally { - leavingServletContainer(request, response); + leavingServletContainer(catalinaRequest, catalinaResponse); } } } @@ -348,170 +308,117 @@ private void doService(final org.glassfish.grizzly.http.server.Request req, } // ------------------------------------------------------ Protected Methods - /** * Parse additional request parameters. */ - protected boolean postParseRequest(final org.glassfish.grizzly.http.server.Request req, - final Request request, - final org.glassfish.grizzly.http.server.Response res, - final Response response, - final boolean v3Enabled) - throws Exception { + protected boolean postParseRequest( + final org.glassfish.grizzly.http.server.Request grizzlyRequest, final Request catalinaRequest, + final org.glassfish.grizzly.http.server.Response grizzlyResponse, final Response catalinaResponse, final boolean v3Enabled) throws Exception { + // XXX the processor may have set a correct scheme and port prior to this point, // in ajp13 protocols dont make sense to get the port from the connector... // otherwise, use connector configuration - request.setSecure(req.isSecure()); + catalinaRequest.setSecure(grizzlyRequest.isSecure()); // URI decoding DataChunk decodedURI; try { - decodedURI = req.getRequest().getRequestURIRef().getDecodedRequestURIBC(); + decodedURI = grizzlyRequest.getRequest().getRequestURIRef().getDecodedRequestURIBC(); } catch (CharConversionException cce) { - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URI"); + catalinaResponse.sendError(SC_BAD_REQUEST, "Invalid URI"); return false; } if (compatWithTomcat || !v3Enabled) { -// decodedURI.duplicate(req.requestURI()); -// try { -// req.getURLDecoder().convert(decodedURI, false); -// } catch (IOException ioe) { -// res.setStatus(400); -// res.setMessage("Invalid URI: " + ioe.getMessage()); -// return false; -// } - - /* GlassFish Issue 2339 - // Normalize decoded URI - if (!normalize(req.decodedURI())) { - res.setStatus(400); - res.setMessage("Invalid URI"); - return false; - } - */ // Set the remote principal - String principal = req.getRemoteUser(); + String principal = grizzlyRequest.getRemoteUser(); if (principal != null) { - request.setUserPrincipal(new CoyotePrincipal(principal)); + catalinaRequest.setUserPrincipal(new CoyotePrincipal(principal)); } // Set the authorization type - String authtype = req.getAuthType(); + String authtype = grizzlyRequest.getAuthType(); if (authtype != null) { - request.setAuthType(authtype); + catalinaRequest.setAuthType(authtype); } - - /* CR 6309511 - // URI character decoding - convertURI(decodedURI, request); - - // Parse session Id - parseSessionId(req, request); - */ - // START CR 6309511 -// URI character decoding -// request.convertURI(decodedURI); - - // START GlassFish Issue 2339 - // Normalize decoded URI -// if (!normalize(decodedURI)) { -// res.setStatus(400); -// res.setMessage("Invalid URI"); -// return false; -// } - // END GlassFish Issue 2339 } - // END CR 6309511 /* - * Remove any parameters from the URI, so they won't be considered - * by the mapping algorithm, and save them in a temporary CharChunk, - * so that any session id param may be parsed once the target - * context, which may use a custom session parameter name, has been - * identified + * Remove any parameters from the URI, so they won't be considered by the mapping algorithm, and save them in a + * temporary CharChunk, so that any session id param may be parsed once the target context, which may use a custom + * session parameter name, has been identified */ - final CharChunk uriParamsCC = request.getURIParams(); + final CharChunk uriParamsCC = catalinaRequest.getURIParams(); final CharChunk uriCC = decodedURI.getCharChunk(); final int semicolon = uriCC.indexOf(';'); if (semicolon > 0) { final int absSemicolon = uriCC.getStart() + semicolon; - uriParamsCC.setChars(uriCC.getBuffer(), absSemicolon, - uriCC.getEnd() - absSemicolon); - decodedURI.setChars(uriCC.getBuffer(), uriCC.getStart(), - absSemicolon - uriCC.getStart()); + uriParamsCC.setChars(uriCC.getBuffer(), absSemicolon, uriCC.getEnd() - absSemicolon); + decodedURI.setChars(uriCC.getBuffer(), uriCC.getStart(), absSemicolon - uriCC.getStart()); } if (compatWithTomcat || !v3Enabled) { - /*mod_jk*/ + /* mod_jk */ DataChunk localDecodedURI = decodedURI; if (semicolon > 0) { - localDecodedURI = req.getNote(DATA_CHUNK); + localDecodedURI = grizzlyRequest.getNote(DATA_CHUNK); if (localDecodedURI == null) { localDecodedURI = DataChunk.newInstance(); - req.setNote(DATA_CHUNK, localDecodedURI); + grizzlyRequest.setNote(DATA_CHUNK, localDecodedURI); } localDecodedURI.duplicate(decodedURI); } - connector.getMapper().map(req.getRequest().serverName(), localDecodedURI, - request.getMappingData()); - MappingData md = request.getMappingData(); - req.setNote(MAPPING_DATA, md); - request.updatePaths(md); + + connector.getMapper() + .map( + grizzlyRequest.getRequest().serverName(), + localDecodedURI, + catalinaRequest.getMappingData()); + + MappingData md = catalinaRequest.getMappingData(); + grizzlyRequest.setNote(MAPPING_DATA, md); + catalinaRequest.updatePaths(md); } - // FIXME: the code below doesnt belongs to here, - // this is only have sense - // in Http11, not in ajp13.. - // At this point the Host header has been processed. - // Override if the proxyPort/proxyHost are set + // FIXME: the code below doesn't belongs to here, this is only have sense in Http11, not in ajp13.. + // At this point the Host header has been processed. Override if the proxyPort/proxyHost are set String proxyName = connector.getProxyName(); int proxyPort = connector.getProxyPort(); if (proxyPort != 0) { - req.setServerPort(proxyPort); + grizzlyRequest.setServerPort(proxyPort); } if (proxyName != null) { - req.setServerName(proxyName); + grizzlyRequest.setServerName(proxyName); } - Context ctx = (Context) request.getMappingData().context; + Context catalinaContext = (Context) catalinaRequest.getMappingData().context; // Parse session id - if (ctx != null) { - if (req.isRequestedSessionIdFromURL() && - Globals.SESSION_PARAMETER_NAME.equals(ctx.getSessionParameterName())) { - request.obtainSessionId(); + if (catalinaContext != null) { + if (grizzlyRequest.isRequestedSessionIdFromURL() && SESSION_PARAMETER_NAME.equals(catalinaContext.getSessionParameterName())) { + catalinaRequest.obtainSessionId(); } else if (!uriParamsCC.isNull()) { -// String sessionParam = ";" + ctx.getSessionParameterName() + "="; - request.parseSessionId(ctx.getSessionParameterName(), uriParamsCC); + catalinaRequest.parseSessionId(catalinaContext.getSessionParameterName(), uriParamsCC); } } - // START GlassFish 1024 - request.setDefaultContext(request.getMappingData().isDefaultContext); - // END GlassFish 1024 + catalinaRequest.setDefaultContext(catalinaRequest.getMappingData().isDefaultContext); + catalinaRequest.setContext(catalinaContext); - // START SJSAS 6253524 - // request.setContext((Context) request.getMappingData().context); - // END SJSAS 6253524 - // START SJSAS 6253524 - request.setContext(ctx); - // END SJSAS 6253524 - - if (ctx != null && !uriParamsCC.isNull()) { - request.parseSessionVersion(uriParamsCC); + if (catalinaContext != null && !uriParamsCC.isNull()) { + catalinaRequest.parseSessionVersion(uriParamsCC); } if (!uriParamsCC.isNull()) { - request.parseJReplica(uriParamsCC); + catalinaRequest.parseJReplica(uriParamsCC); } - request.setWrapper((Wrapper) request.getMappingData().wrapper); + catalinaRequest.setWrapper((Wrapper) catalinaRequest.getMappingData().wrapper); // Filter trace method - if (!connector.getAllowTrace() && Method.TRACE.equals(req.getMethod())) { - Wrapper wrapper = request.getWrapper(); + if (!connector.getAllowTrace() && Method.TRACE.equals(grizzlyRequest.getMethod())) { + Wrapper wrapper = catalinaRequest.getWrapper(); String header = null; if (wrapper != null) { String[] methods = wrapper.getServletMethods(); @@ -529,113 +436,86 @@ protected boolean postParseRequest(final org.glassfish.grizzly.http.server.Reque } } } - res.setStatus(405, "TRACE method is not allowed"); - res.addHeader("Allow", header); + grizzlyResponse.setStatus(405, "TRACE method is not allowed"); + grizzlyResponse.addHeader("Allow", header); + return false; } // Possible redirect - DataChunk redirectPathMB = request.getMappingData().redirectPath; - // START SJSAS 6253524 - // if (!redirectPathMB.isNull()) { - // END SJSAS 6253524 - // START SJSAS 6253524 - if (!redirectPathMB.isNull() - && (!ctx.hasAdHocPaths() - || (ctx.getAdHocServletName(((HttpServletRequest) - request.getRequest()).getServletPath()) == null))) { - // END SJSAS 6253524 + DataChunk redirectPathMB = catalinaRequest.getMappingData().redirectPath; + if (!redirectPathMB.isNull() && (!catalinaContext.hasAdHocPaths() || (catalinaContext.getAdHocServletName(catalinaRequest.getRequest().getServletPath()) == null))) { String redirectPath = redirectPathMB.toString(); - String query = request.getQueryString(); - if (request.isRequestedSessionIdFromURL()) { - // This is not optimal, but as this is not very common, it - // shouldn't matter - redirectPath = redirectPath + ";" + ctx.getSessionParameterName() + "=" - + request.getRequestedSessionId(); - } - // START GlassFish 936 - redirectPath = response.encode(redirectPath); - // END GlassFish 936 + String query = catalinaRequest.getQueryString(); + if (catalinaRequest.isRequestedSessionIdFromURL()) { + // This is not optimal, but as this is not very common, it shouldn't matter + redirectPath = redirectPath + ";" + catalinaContext.getSessionParameterName() + "=" + catalinaRequest.getRequestedSessionId(); + } + + redirectPath = catalinaResponse.encode(redirectPath); if (query != null) { - // This is not optimal, but as this is not very common, it - // shouldn't matter + // This is not optimal, but as this is not very common, it shouldn't matter redirectPath = redirectPath + "?" + query; } - // START CR 6590921 - boolean authPassthroughEnabled = - connector.getAuthPassthroughEnabled(); + boolean authPassthroughEnabled = connector.getAuthPassthroughEnabled(); ProxyHandler proxyHandler = connector.getProxyHandler(); if (authPassthroughEnabled && proxyHandler != null) { - - if (proxyHandler.getSSLKeysize( - (HttpServletRequest)request.getRequest()) > 0) { - request.setSecure(true); + if (proxyHandler.getSSLKeysize(catalinaRequest.getRequest()) > 0) { + catalinaRequest.setSecure(true); } } - // END CR 6590921 + // Issue a permanent redirect // Validating the redirectPath for header injection if (InputValidationUtil.validateStringforCRLF(redirectPath)) { - response.sendError(403, "Forbidden"); + catalinaResponse.sendError(403, "Forbidden"); } else { - response.sendRedirect(InputValidationUtil.removeLinearWhiteSpaces(redirectPath), - false); + catalinaResponse.sendRedirect(InputValidationUtil.removeLinearWhiteSpaces(redirectPath), false); } return false; } // Parse session Id - /* CR 6309511 - parseSessionCookiesId(req, request); - */ - // START CR 6309511 - request.parseSessionCookiesId(); - // END CR 6309511 - - // START SJSAS 6346226 - request.parseJrouteCookie(); - // END SJSAS 6346226 + catalinaRequest.parseSessionCookiesId(); + catalinaRequest.parseJrouteCookie(); return true; } - /** * Normalize URI. *

- * This method normalizes "\", "//", "/./" and "/../". This method will - * return false when trying to go above the root, or if the URI contains - * a null byte. + * This method normalizes "\", "//", "/./" and "/../". This method will return false when trying to go above the root, + * or if the URI contains a null byte. * * @param uriMB URI to be normalized */ public static boolean normalize(MessageBytes uriMB) { - int type = uriMB.getType(); if (type == MessageBytes.T_CHARS) { return normalizeChars(uriMB); - } else { - return normalizeBytes(uriMB); } - } + return normalizeBytes(uriMB); + } private static boolean normalizeBytes(MessageBytes uriMB) { - ByteChunk uriBC = uriMB.getByteChunk(); byte[] b = uriBC.getBytes(); int start = uriBC.getStart(); int end = uriBC.getEnd(); // An empty URL is not acceptable - if (start == end) + if (start == end) { return false; + } // URL * is acceptable - if ((end - start == 1) && b[start] == (byte) '*') - return true; + if ((end - start == 1) && b[start] == (byte) '*') { + return true; + } int pos = 0; int index = 0; @@ -676,9 +556,7 @@ private static boolean normalizeBytes(MessageBytes uriMB) { // Note: It is possible to extend the URI by 1 without any side effect // as the next character is a non-significant WS. if (((end - start) > 2) && (b[end - 1] == (byte) '.')) { - if ((b[end - 2] == (byte) '/') - || ((b[end - 2] == (byte) '.') - && (b[end - 3] == (byte) '/'))) { + if ((b[end - 2] == (byte) '/') || ((b[end - 2] == (byte) '.') && (b[end - 3] == (byte) '/'))) { b[end] = (byte) '/'; end++; } @@ -691,10 +569,10 @@ private static boolean normalizeBytes(MessageBytes uriMB) { // Resolve occurrences of "/./" in the normalized path while (true) { index = uriBC.indexOf("/./", 0, 3, index); - if (index < 0) + if (index < 0) { break; - copyBytes(b, start + index, start + index + 2, - end - start - index - 2); + } + copyBytes(b, start + index, start + index + 2, end - start - index - 2); end = end - 2; uriBC.setEnd(end); } @@ -704,19 +582,20 @@ private static boolean normalizeBytes(MessageBytes uriMB) { // Resolve occurrences of "/../" in the normalized path while (true) { index = uriBC.indexOf("/../", 0, 4, index); - if (index < 0) + if (index < 0) { break; + } // Prevent from going outside our context - if (index == 0) + if (index == 0) { return false; + } int index2 = -1; - for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { + for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos--) { if (b[pos] == (byte) '/') { index2 = pos; } } - copyBytes(b, start + index2, start + index + 3, - end - start - index - 3); + copyBytes(b, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; uriBC.setEnd(end); index = index2; @@ -725,20 +604,18 @@ private static boolean normalizeBytes(MessageBytes uriMB) { uriBC.setBytes(b, start, end); return true; - } - - private static boolean normalizeChars(MessageBytes uriMB) { - - CharChunk uriCC = uriMB.getCharChunk(); - char[] c = uriCC.getChars(); - int start = uriCC.getStart(); - int end = uriCC.getEnd(); + private static boolean normalizeChars(MessageBytes uriMessageBytes) { + CharChunk uriCharChunk = uriMessageBytes.getCharChunk(); + char[] c = uriCharChunk.getChars(); + int start = uriCharChunk.getStart(); + int end = uriCharChunk.getEnd(); // URL * is acceptable - if ((end - start == 1) && c[start] == (char) '*') - return true; + if ((end - start == 1) && c[start] == '*') { + return true; + } int pos = 0; int index = 0; @@ -746,9 +623,9 @@ private static boolean normalizeChars(MessageBytes uriMB) { // Replace '\' with '/' // Check for null char for (pos = start; pos < end; pos++) { - if (c[pos] == (char) '\\') { + if (c[pos] == '\\') { if (ALLOW_BACKSLASH) { - c[pos] = (char) '/'; + c[pos] = '/'; } else { return false; } @@ -759,15 +636,15 @@ private static boolean normalizeChars(MessageBytes uriMB) { } // The URL must start with '/' - if (c[start] != (char) '/') { + if (c[start] != '/') { return false; } // Replace "//" with "/" if (COLLAPSE_ADJACENT_SLASHES) { for (pos = start; pos < (end - 1); pos++) { - if (c[pos] == (char) '/') { - while ((pos + 1 < end) && (c[pos + 1] == (char) '/')) { + if (c[pos] == '/') { + while ((pos + 1 < end) && (c[pos + 1] == '/')) { copyChars(c, pos, pos + 1, end - pos - 1); end--; } @@ -778,66 +655,61 @@ private static boolean normalizeChars(MessageBytes uriMB) { // If the URI ends with "/." or "/..", then we append an extra "/" // Note: It is possible to extend the URI by 1 without any side effect // as the next character is a non-significant WS. - if (((end - start) > 2) && (c[end - 1] == (char) '.')) { - if ((c[end - 2] == (char) '/') - || ((c[end - 2] == (char) '.') - && (c[end - 3] == (char) '/'))) { - c[end] = (char) '/'; + if (((end - start) > 2) && (c[end - 1] == '.')) { + if ((c[end - 2] == '/') || ((c[end - 2] == '.') && (c[end - 3] == '/'))) { + c[end] = '/'; end++; } } - uriCC.setEnd(end); + uriCharChunk.setEnd(end); index = 0; // Resolve occurrences of "/./" in the normalized path while (true) { - index = uriCC.indexOf("/./", 0, 3, index); - if (index < 0) + index = uriCharChunk.indexOf("/./", 0, 3, index); + if (index < 0) { break; - copyChars(c, start + index, start + index + 2, - end - start - index - 2); + } + copyChars(c, start + index, start + index + 2, end - start - index - 2); end = end - 2; - uriCC.setEnd(end); + uriCharChunk.setEnd(end); } index = 0; // Resolve occurrences of "/../" in the normalized path while (true) { - index = uriCC.indexOf("/../", 0, 4, index); - if (index < 0) + index = uriCharChunk.indexOf("/../", 0, 4, index); + if (index < 0) { break; + } // Prevent from going outside our context - if (index == 0) + if (index == 0) { return false; + } int index2 = -1; - for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { - if (c[pos] == (char) '/') { + for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos--) { + if (c[pos] == '/') { index2 = pos; } } - copyChars(c, start + index2, start + index + 3, - end - start - index - 3); + copyChars(c, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; - uriCC.setEnd(end); + uriCharChunk.setEnd(end); index = index2; } - uriCC.setChars(c, start, end); + uriCharChunk.setChars(c, start, end); return true; - } - // ------------------------------------------------------ Protected Methods - /** - * Copy an array of bytes to a different position. Used during - * normalization. + * Copy an array of bytes to a different position. Used during normalization. */ protected static void copyBytes(byte[] b, int dest, int src, int len) { for (int pos = 0; pos < len; pos++) { @@ -845,10 +717,8 @@ protected static void copyBytes(byte[] b, int dest, int src, int len) { } } - /** - * Copy an array of chars to a different position. Used during - * normalization. + * Copy an array of chars to a different position. Used during normalization. */ private static void copyChars(char[] c, int dest, int src, int len) { for (int pos = 0; pos < len; pos++) { @@ -856,17 +726,15 @@ private static void copyChars(char[] c, int dest, int src, int len) { } } - /** * Log a message on the Logger associated with our Container (if any) * * @param message Message to be logged */ protected void log(String message) { - log.log(Level.INFO, message); + log.log(INFO, message); } - /** * Log a message on the Logger associated with our Container (if any) * @@ -874,58 +742,25 @@ protected void log(String message) { * @param throwable Associated exception */ protected void log(String message, Throwable throwable) { - log.log(Level.SEVERE, message, throwable); + log.log(SEVERE, message, throwable); } - - /** - * Character conversion of the a US-ASCII MessageBytes. - */ - /* CR 6309511 - protected void convertMB(MessageBytes mb) { - - // This is of course only meaningful for bytes - if (mb.getType() != MessageBytes.T_BYTES) - return; - - ByteChunk bc = mb.getByteChunk(); - CharChunk cc = mb.getCharChunk(); - cc.allocate(bc.getLength(), -1); - - // Default encoding: fast conversion - byte[] bbuf = bc.getBuffer(); - char[] cbuf = cc.getBuffer(); - int start = bc.getStart(); - for (int i = 0; i < bc.getLength(); i++) { - cbuf[i] = (char) (bbuf[i + start] & 0xff); - } - mb.setChars(cbuf, 0, bc.getLength()); - - } - */ - - - // START SJSAS 6349248 /** - * Notify all container event listeners that a particular event has - * occurred for this Adapter. The default implementation performs - * this notification synchronously using the calling thread. + * Notify all container event listeners that a particular event has occurred for this Adapter. The default + * implementation performs this notification synchronously using the calling thread. * * @param type Event type * @param data Event data */ public void fireAdapterEvent(String type, Object data) { - if ( connector != null && connector.getContainer() != null) { - try{ - ((ContainerBase)connector.getContainer()) - .fireContainerEvent(type,data); - } catch (Throwable t){ - log.log(Level.SEVERE, LogFacade.REQUEST_PROCESSING_EXCEPTION, t); + if (connector != null && connector.getContainer() != null) { + try { + ((ContainerBase) connector.getContainer()).fireContainerEvent(type, data); + } catch (Throwable t) { + log.log(SEVERE, REQUEST_PROCESSING_EXCEPTION, t); } } } - // END SJSAS 6349248 - /** * Return true when an instance is executed the same way it does in Tomcat. @@ -934,18 +769,15 @@ public boolean isCompatWithTomcat() { return compatWithTomcat; } - /** - * true if this class needs to be compatible with Tomcat - * Adapter class. Since Tomcat Adapter implementation doesn't support - * the afterService method, the afterService method must be invoked - * inside the service method. + * true if this class needs to be compatible with Tomcat Adapter class. Since Tomcat Adapter implementation + * doesn't support the afterService method, the afterService method must be invoked inside the service method. */ public void setCompatWithTomcat(boolean compatWithTomcat) { this.compatWithTomcat = compatWithTomcat; // Add server header - if (compatWithTomcat){ + if (compatWithTomcat) { serverName = "Apache/" + serverName; } else { // Recalculate. @@ -953,7 +785,6 @@ public void setCompatWithTomcat(boolean compatWithTomcat) { } } - /** * Gets the port of this CoyoteAdapter. * @@ -964,31 +795,30 @@ public int getPort() { } /** - * AfterServiceListener, which is responsible for recycle catalina request and response - * objects. + * AfterServiceListener, which is responsible for recycle catalina request and response objects. */ static final class CatalinaAfterServiceListener implements AfterServiceListener { @Override - public void onAfterService(final org.glassfish.grizzly.http.server.Request request) { - final Request servletRequest = request.getNote(CATALINA_REQUEST_NOTE); - final Response servletResponse = request.getNote(CATALINA_RESPONSE_NOTE); + public void onAfterService(final org.glassfish.grizzly.http.server.Request grizzlyRequest) { + final Request catalinaRequest = grizzlyRequest.getNote(CATALINA_REQUEST_NOTE); + final Response catalinaResponse = grizzlyRequest.getNote(CATALINA_RESPONSE_NOTE); - if (servletRequest != null) { + if (catalinaRequest != null) { try { - if (!servletRequest.isUpgrade()) { - servletResponse.finishResponse(); + if (!catalinaRequest.isUpgrade()) { + catalinaResponse.finishResponse(); } else { - servletResponse.setUpgrade(servletRequest.isUpgrade()); + catalinaResponse.setUpgrade(catalinaRequest.isUpgrade()); } } catch (Exception e) { - log.log(Level.SEVERE, LogFacade.REQUEST_PROCESSING_EXCEPTION, e); + log.log(SEVERE, REQUEST_PROCESSING_EXCEPTION, e); } finally { try { - servletRequest.unlockSession(); + catalinaRequest.unlockSession(); } finally { - servletRequest.recycle(); - servletResponse.recycle(); + catalinaRequest.recycle(); + catalinaResponse.recycle(); } } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java index c99c443587f..4ede4601ad4 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java @@ -349,7 +349,7 @@ protected synchronized Object initialValue() { protected String requestedSessionCookiePath; // Temporary holder for URI params from which session id is parsed - protected CharChunk uriParamsCC = new CharChunk(); + protected CharChunk uriParamsCharChunk = new CharChunk(); /** * Was the requested session ID received in a URL? @@ -424,9 +424,9 @@ protected synchronized Object initialValue() { private String requestURI; /** - * Coyote request. + * Grizzly request. */ - protected org.glassfish.grizzly.http.server.Request coyoteRequest; + protected org.glassfish.grizzly.http.server.Request grizzlyRequest; /** * The facade associated with this request. @@ -532,8 +532,8 @@ public Request() { * * @param grizzlyRequest The Coyote request */ - public void setCoyoteRequest(org.glassfish.grizzly.http.server.Request grizzlyRequest) { - this.coyoteRequest = grizzlyRequest; + public void setGrizzlyRequest(org.glassfish.grizzly.http.server.Request grizzlyRequest) { + this.grizzlyRequest = grizzlyRequest; inputBuffer.setRequest(grizzlyRequest); inputBuffer.setRequest(this); } @@ -541,8 +541,8 @@ public void setCoyoteRequest(org.glassfish.grizzly.http.server.Request grizzlyRe /** * Get the Coyote request. */ - public org.glassfish.grizzly.http.server.Request getCoyoteRequest() { - return this.coyoteRequest; + public org.glassfish.grizzly.http.server.Request getGrizzlyRequest() { + return this.grizzlyRequest; } /** @@ -610,7 +610,7 @@ public void recycle() { requestedSessionId = null; requestedSessionCookiePath = null; requestedSessionURL = false; - uriParamsCC.recycle(); + uriParamsCharChunk.recycle(); sessionTracker.reset(); /* @@ -689,7 +689,7 @@ public HttpUpgradeHandler getHttpUpgradeHandler() { */ @Override public String getAuthorization() { - return coyoteRequest.getHeader(AUTHORIZATION_HEADER); + return grizzlyRequest.getHeader(AUTHORIZATION_HEADER); } /** @@ -1064,7 +1064,7 @@ public void setNote(String name, Object value) { */ @Override public void setContentLength(int length) { - coyoteRequest.getRequest().setContentLength(length); + grizzlyRequest.getRequest().setContentLength(length); } /** @@ -1124,7 +1124,7 @@ public void setSecure(boolean secure) { */ @Override public void setServerName(String name) { - coyoteRequest.setServerName(name); + grizzlyRequest.setServerName(name); } /** @@ -1134,7 +1134,7 @@ public void setServerName(String name) { */ @Override public void setServerPort(int port) { - coyoteRequest.setServerPort(port); + grizzlyRequest.setServerPort(port); } /** @@ -1180,20 +1180,20 @@ public Object getAttribute(String name) { return attribute; } - attribute = coyoteRequest.getAttribute(name); + attribute = grizzlyRequest.getAttribute(name); if (attribute != null) { return attribute; } if (Globals.SSL_CERTIFICATE_ATTR.equals(name)) { // @TODO Implement SSL rehandshake - RequestUtils.populateCertificateAttribute(coyoteRequest); + RequestUtils.populateCertificateAttribute(grizzlyRequest); attribute = getAttribute(CERTIFICATES_ATTR); if (attribute != null) { attributes.put(name, attribute); } } else if (isSSLAttribute(name)) { - RequestUtils.populateSSLAttributes(coyoteRequest); + RequestUtils.populateSSLAttributes(grizzlyRequest); attribute = attributes.get(name); } @@ -1226,7 +1226,7 @@ public Enumeration getAttributeNames() { */ @Override public String getCharacterEncoding() { - return coyoteRequest.getCharacterEncoding(); + return grizzlyRequest.getCharacterEncoding(); } /** @@ -1234,7 +1234,7 @@ public String getCharacterEncoding() { */ @Override public int getContentLength() { - return coyoteRequest.getContentLength(); + return grizzlyRequest.getContentLength(); } /** @@ -1242,7 +1242,7 @@ public int getContentLength() { */ @Override public long getContentLengthLong() { - return coyoteRequest.getContentLengthLong(); + return grizzlyRequest.getContentLengthLong(); } /** @@ -1250,7 +1250,7 @@ public long getContentLengthLong() { */ @Override public String getContentType() { - return coyoteRequest.getContentType(); + return grizzlyRequest.getContentType(); } /** @@ -1281,7 +1281,7 @@ public ServletInputStream getInputStream() throws IOException { */ @Override public Locale getLocale() { - return coyoteRequest.getLocale(); + return grizzlyRequest.getLocale(); } /** @@ -1291,7 +1291,7 @@ public Locale getLocale() { */ @Override public Enumeration getLocales() { - return new Enumerator<>(coyoteRequest.getLocales()); + return new Enumerator<>(grizzlyRequest.getLocales()); } private void processParameters() { @@ -1320,7 +1320,7 @@ private void processParameters() { public String getParameter(String name) { processParameters(); - return coyoteRequest.getParameter(name); + return grizzlyRequest.getParameter(name); } /** @@ -1354,7 +1354,7 @@ public Map getParameterMap() { public Enumeration getParameterNames() { processParameters(); - return new Enumerator<>(coyoteRequest.getParameterNames()); + return new Enumerator<>(grizzlyRequest.getParameterNames()); } /** @@ -1366,7 +1366,7 @@ public Enumeration getParameterNames() { public String[] getParameterValues(String name) { processParameters(); - return coyoteRequest.getParameterValues(name); + return grizzlyRequest.getParameterValues(name); } /** @@ -1374,7 +1374,7 @@ public String[] getParameterValues(String name) { */ @Override public String getProtocol() { - return coyoteRequest.getProtocol().getProtocolString(); + return grizzlyRequest.getProtocol().getProtocolString(); } /** @@ -1425,7 +1425,7 @@ public String getRemoteAddr() { InetAddress inet = socket.getInetAddress(); remoteAddr = inet.getHostAddress(); } else { - remoteAddr = coyoteRequest.getRemoteAddr(); + remoteAddr = grizzlyRequest.getRemoteAddr(); } } @@ -1456,7 +1456,7 @@ public String getRemoteHost() { InetAddress inet = socket.getInetAddress(); remoteHost = inet.getHostName(); } else { - remoteHost = coyoteRequest.getRemoteHost(); + remoteHost = grizzlyRequest.getRemoteHost(); } } @@ -1472,7 +1472,7 @@ public int getRemotePort() { if (socket != null) { remotePort = socket.getPort(); } else { - remotePort = coyoteRequest.getRemotePort(); + remotePort = grizzlyRequest.getRemotePort(); } } @@ -1489,7 +1489,7 @@ public String getLocalName() { InetAddress inet = socket.getLocalAddress(); localName = inet.getHostName(); } else { - localName = coyoteRequest.getLocalName(); + localName = grizzlyRequest.getLocalName(); } } @@ -1506,7 +1506,7 @@ public String getLocalAddr() { InetAddress inet = socket.getLocalAddress(); localAddr = inet.getHostAddress(); } else { - localAddr = coyoteRequest.getLocalAddr(); + localAddr = grizzlyRequest.getLocalAddr(); } } @@ -1522,7 +1522,7 @@ public int getLocalPort() { if (socket != null) { localPort = socket.getLocalPort(); } else { - localPort = coyoteRequest.getLocalPort(); + localPort = grizzlyRequest.getLocalPort(); } } @@ -1589,7 +1589,7 @@ public String getScheme() { } } - return coyoteRequest.getScheme(); + return grizzlyRequest.getScheme(); } /** @@ -1597,7 +1597,7 @@ public String getScheme() { */ @Override public String getServerName() { - return coyoteRequest.getServerName(); + return grizzlyRequest.getServerName(); } /** @@ -1613,7 +1613,7 @@ public int getServerPort() { } } - return coyoteRequest.getServerPort(); + return grizzlyRequest.getServerPort(); } /** @@ -1719,7 +1719,7 @@ public void setAttribute(String name, Object value) { // Pass special attributes to the grizzly layer if (name.startsWith("grizzly.")) { - coyoteRequest.setAttribute(name, value); + grizzlyRequest.setAttribute(name, value); } // Notify interested application event listeners @@ -1799,7 +1799,7 @@ public String run() throws UnsupportedEncodingException { } // Save the validated encoding - coyoteRequest.setCharacterEncoding(enc); + grizzlyRequest.setCharacterEncoding(enc); } /** @@ -1954,7 +1954,7 @@ public void addCookie(Cookie cookie) { */ @Override public void addHeader(String name, String value) { - coyoteRequest.getRequest().getHeaders().addValue(name).setString(value); + grizzlyRequest.getRequest().getHeaders().addValue(name).setString(value); } /** @@ -1977,7 +1977,7 @@ public void addLocale(Locale locale) { */ @Override public void addParameter(String name, String values[]) { - coyoteRequest.addParameter(name, values); + grizzlyRequest.addParameter(name, values); } /** @@ -1994,7 +1994,7 @@ public void clearCookies() { */ @Override public void clearHeaders() { - coyoteRequest.getRequest().getHeaders().recycle(); + grizzlyRequest.getRequest().getHeaders().recycle(); } /** @@ -2010,8 +2010,8 @@ public void clearLocales() { */ @Override public void clearParameters() { - coyoteRequest.getParameters().recycle(); - coyoteRequest.getParameters().setQueryStringEncoding(Charsets.lookupCharset(getConnector().getURIEncoding())); + grizzlyRequest.getParameters().recycle(); + grizzlyRequest.getParameters().setQueryStringEncoding(Charsets.lookupCharset(getConnector().getURIEncoding())); } @Override @@ -2020,7 +2020,7 @@ public void replayPayload(byte[] payloadByteArray) { return; } - coyoteRequest.replayPayload(Buffers.wrap(coyoteRequest.getContext().getMemoryManager(), payloadByteArray)); + grizzlyRequest.replayPayload(Buffers.wrap(grizzlyRequest.getContext().getMemoryManager(), payloadByteArray)); } /** @@ -2044,7 +2044,7 @@ public void setAuthType(String type) { */ @Override public void setMethod(String method) { - coyoteRequest.setMethod(method); + grizzlyRequest.setMethod(method); } /** @@ -2057,7 +2057,7 @@ public void setMethod(String method) { */ @Override public void setQueryString(String query) { - coyoteRequest.setQueryString(query); + grizzlyRequest.setQueryString(query); } /** @@ -2141,7 +2141,7 @@ public void setRequestedSessionURL(boolean flag) { */ @Override public void setRequestURI(String uri) { - coyoteRequest.setRequestURI(uri); + grizzlyRequest.setRequestURI(uri); } /** @@ -2163,9 +2163,9 @@ public String getDecodedRequestURI() { public String getDecodedRequestURI(boolean maskDefaultContextMapping) { try { if (maskDefaultContextMapping || !isDefaultContext) { - return coyoteRequest.getDecodedRequestURI(); + return grizzlyRequest.getDecodedRequestURI(); } else { - return getContextPath() + coyoteRequest.getDecodedRequestURI(); + return getContextPath() + grizzlyRequest.getDecodedRequestURI(); } } catch (CharConversionException e) { throw new RuntimeException(e.getMessage(), e); @@ -2296,7 +2296,7 @@ public long getDateHeader(String name) { */ @Override public String getHeader(String name) { - return coyoteRequest.getHeader(name); + return grizzlyRequest.getHeader(name); } /** @@ -2306,7 +2306,7 @@ public String getHeader(String name) { */ @Override public Enumeration getHeaders(String name) { - return new Enumerator<>(coyoteRequest.getHeaders(name).iterator()); + return new Enumerator<>(grizzlyRequest.getHeaders(name).iterator()); } /** @@ -2314,7 +2314,7 @@ public Enumeration getHeaders(String name) { */ @Override public Enumeration getHeaderNames() { - return new Enumerator<>(coyoteRequest.getHeaderNames().iterator()); + return new Enumerator<>(grizzlyRequest.getHeaderNames().iterator()); } /** @@ -2336,12 +2336,12 @@ public int getIntHeader(String name) { @Override public Map getTrailerFields() { - return coyoteRequest.getTrailers(); + return grizzlyRequest.getTrailers(); } @Override public boolean isTrailerFieldsReady() { - return coyoteRequest.areTrailersAvailable(); + return grizzlyRequest.areTrailersAvailable(); } /** @@ -2349,7 +2349,7 @@ public boolean isTrailerFieldsReady() { */ @Override public String getMethod() { - return coyoteRequest.getMethod().getMethodString(); + return grizzlyRequest.getMethod().getMethodString(); } /** @@ -2379,8 +2379,8 @@ public String getPathTranslated() { @Override public PushBuilder newPushBuilder() { Http2Stream http2Stream = null; - if (coyoteRequest != null) { - http2Stream = (Http2Stream) coyoteRequest.getAttribute(Http2Stream.HTTP2_STREAM_ATTRIBUTE); + if (grizzlyRequest != null) { + http2Stream = (Http2Stream) grizzlyRequest.getAttribute(Http2Stream.HTTP2_STREAM_ATTRIBUTE); } if (http2Stream != null && http2Stream.isPushEnabled()) { @@ -2395,7 +2395,7 @@ public PushBuilder newPushBuilder() { */ @Override public String getQueryString() { - String queryString = coyoteRequest.getQueryString(); + String queryString = grizzlyRequest.getQueryString(); if (queryString == null || "".equals(queryString)) { return null; @@ -2450,14 +2450,14 @@ public String getRequestURI() { */ public String getRequestURI(boolean maskDefaultContextMapping) { if (maskDefaultContextMapping) { - return coyoteRequest.getRequestURI(); + return grizzlyRequest.getRequestURI(); } if (requestURI == null) { if (isDefaultContext) { - requestURI = getContextPath() + coyoteRequest.getRequestURI(); + requestURI = getContextPath() + grizzlyRequest.getRequestURI(); } else { - requestURI = coyoteRequest.getRequestURI(); + requestURI = grizzlyRequest.getRequestURI(); } } @@ -2764,7 +2764,7 @@ public T upgrade(Class handlerClass) throws IO throw new ServletException(t); } httpUpgradeHandler = handler; - coyoteRequest.getResponse().suspend(); + grizzlyRequest.getResponse().suspend(); return handler; } @@ -2958,7 +2958,7 @@ protected void configureSessionCookie(Cookie cookie) { protected void parseCookies() { cookiesParsed = true; - org.glassfish.grizzly.http.Cookie[] serverCookies = coyoteRequest.getCookies(); + org.glassfish.grizzly.http.Cookie[] serverCookies = grizzlyRequest.getCookies(); int count = serverCookies.length; if (count <= 0) { return; @@ -3033,7 +3033,7 @@ protected byte[] getPostBody() throws IOException { * Read post body in an array. */ protected int readPostBody(byte body[], int len) throws IOException { - Buffer b = coyoteRequest.getPostBody(len).duplicate(); + Buffer b = grizzlyRequest.getPostBody(len).duplicate(); final int length = b.limit() - b.position(); b.get(body, b.position(), length); return length; @@ -3064,18 +3064,18 @@ protected static final boolean isAlpha(String value) { */ protected void obtainSessionId() { setRequestedSessionURL(true); - setJrouteId(coyoteRequest.getJrouteId()); - setRequestedSessionId(coyoteRequest.getRequestedSessionId()); + setJrouteId(grizzlyRequest.getJrouteId()); + setRequestedSessionId(grizzlyRequest.getRequestedSessionId()); } /** * Parse session id in URL. */ - protected void parseSessionId(String sessionParameterName, CharChunk uriBB) { + protected void parseSessionId(String sessionParameterName, CharChunk uriCharChunk) { // Parse session ID, and extract it from the decoded request URI String sessionParam = ";" + sessionParameterName + "="; - String sessionId = parseParameterFromRequestURI(uriBB, sessionParam); + String sessionId = parseParameterFromRequestURI(uriCharChunk, sessionParam); if (sessionId != null) { int jrouteIndex = sessionId.lastIndexOf(':'); @@ -3093,7 +3093,7 @@ protected void parseSessionId(String sessionParameterName, CharChunk uriBB) { /* * Parse the session id from the encoded URI only if the encoded URI is not null, to allow for lazy evaluation */ - if (coyoteRequest.getRequestURI() != null) { + if (grizzlyRequest.getRequestURI() != null) { removeParameterFromRequestURI(sessionParam); } @@ -3153,21 +3153,21 @@ private void addSessionCookie() { * @param parameter of the form ";" + parameterName + "=" * @return parameterValue */ - private String parseParameterFromRequestURI(CharChunk uriCC, String parameter) { + private String parseParameterFromRequestURI(CharChunk uriCharChunk, String parameter) { String parameterValue = null; - int semicolon = uriCC.indexOf(parameter, 0, parameter.length(), 0); + int semicolon = uriCharChunk.indexOf(parameter, 0, parameter.length(), 0); if (semicolon >= 0) { - int start = uriCC.getStart(); - int end = uriCC.getEnd(); + int start = uriCharChunk.getStart(); + int end = uriCharChunk.getEnd(); int parameterStart = start + semicolon + parameter.length(); - int semicolon2 = uriCC.indexOf(';', semicolon + parameter.length()); + int semicolon2 = uriCharChunk.indexOf(';', semicolon + parameter.length()); if (semicolon2 >= 0) { - parameterValue = new String(uriCC.getBuffer(), parameterStart, semicolon2 - semicolon - parameter.length()); + parameterValue = new String(uriCharChunk.getBuffer(), parameterStart, semicolon2 - semicolon - parameter.length()); } else { - parameterValue = new String(uriCC.getBuffer(), parameterStart, end - parameterStart); + parameterValue = new String(uriCharChunk.getBuffer(), parameterStart, end - parameterStart); } } @@ -3183,22 +3183,22 @@ private String parseParameterFromRequestURI(CharChunk uriCC, String parameter) { private void removeParameterFromRequestURI(String parameter) { int semicolon, semicolon2; - final DataChunk uriBC = coyoteRequest.getRequest().getRequestURIRef().getRequestURIBC(); + final DataChunk uriDataChunk = grizzlyRequest.getRequest().getRequestURIRef().getRequestURIBC(); - semicolon = uriBC.indexOf(parameter, 0); + semicolon = uriDataChunk.indexOf(parameter, 0); if (semicolon > 0) { - semicolon2 = uriBC.indexOf(';', semicolon + parameter.length()); + semicolon2 = uriDataChunk.indexOf(';', semicolon + parameter.length()); final int end; if (semicolon2 >= 0) { end = semicolon2; - uriBC.notifyDirectUpdate(); + uriDataChunk.notifyDirectUpdate(); } else { - end = uriBC.getLength(); + end = uriDataChunk.getLength(); } - uriBC.delete(semicolon, end); + uriDataChunk.delete(semicolon, end); } } @@ -3231,7 +3231,7 @@ void parseSessionVersionString(String sessionVersionString) { * Parses the value of the JROUTE cookie, if present. */ void parseJrouteCookie() { - org.glassfish.grizzly.http.Cookie[] serverCookies = coyoteRequest.getCookies(); + org.glassfish.grizzly.http.Cookie[] serverCookies = grizzlyRequest.getCookies(); int count = serverCookies.length; if (count <= 0) { return; @@ -3281,7 +3281,7 @@ protected void parseSessionCookiesId() { } // Parse session id from cookies - org.glassfish.grizzly.http.Cookie[] serverCookies = coyoteRequest.getCookies(); + org.glassfish.grizzly.http.Cookie[] serverCookies = grizzlyRequest.getCookies(); int count = serverCookies.length; if (count <= 0) { return; @@ -3299,23 +3299,18 @@ protected void parseSessionCookiesId() { if (!isRequestedSessionIdFromCookie()) { // Accept only the first session id cookie setRequestedSessionId(scookie.getValue()); - // TODO: Pass cookie path into - // getSessionVersionFromCookie() - String sessionVersionString = getSessionVersionFromCookie(); - parseSessionVersionString(sessionVersionString); + // TODO: Pass cookie path into getSessionVersionFromCookie() + parseSessionVersionString(getSessionVersionFromCookie()); setRequestedSessionCookie(true); - // TBD: ServerCookie#getSecure currently always returns - // false. + // TBD: ServerCookie#getSecure currently always returns false. setRequestedSessionIdFromSecureCookie(scookie.isSecure()); setRequestedSessionURL(false); } else { if (!isRequestedSessionIdValid()) { // Replace the session id until one is valid setRequestedSessionId(scookie.getValue()); - // TODO: Pass cookie path into - // getSessionVersionFromCookie() - String sessionVersionString = getSessionVersionFromCookie(); - parseSessionVersionString(sessionVersionString); + // TODO: Pass cookie path into getSessionVersionFromCookie() + parseSessionVersionString(getSessionVersionFromCookie()); } } } @@ -3332,7 +3327,7 @@ private String getSessionVersionFromCookie() { return null; } - org.glassfish.grizzly.http.Cookie[] serverCookies = coyoteRequest.getCookies(); + org.glassfish.grizzly.http.Cookie[] serverCookies = grizzlyRequest.getCookies(); int count = serverCookies.length; if (count <= 0) { return null; @@ -3352,7 +3347,7 @@ private String getSessionVersionFromCookie() { * @return temporary holder for URI params from which session id is parsed */ CharChunk getURIParams() { - return uriParamsCC; + return uriParamsCharChunk; } /** @@ -3483,7 +3478,7 @@ public boolean onTimeout(final org.glassfish.grizzly.http.server.Response respon } }; - coyoteRequest.getResponse().suspend(-1, TimeUnit.MILLISECONDS, requestCompletionHandler, timeoutHandler); + grizzlyRequest.getResponse().suspend(-1, TimeUnit.MILLISECONDS, requestCompletionHandler, timeoutHandler); asyncStartedThread = Thread.currentThread(); } @@ -3516,7 +3511,7 @@ public void disableAsyncSupport() { } void setAsyncTimeout(long timeout) { - coyoteRequest.getResponse().getSuspendContext().setTimeout(timeout, TimeUnit.MILLISECONDS); + grizzlyRequest.getResponse().getSuspendContext().setTimeout(timeout, TimeUnit.MILLISECONDS); } @@ -3548,12 +3543,12 @@ void asyncComplete() { if (asyncStartedThread != Thread.currentThread() || !asyncContext.isOkToConfigure()) { // it's not safe to just mark response as resumed - coyoteRequest.getResponse().resume(); + grizzlyRequest.getResponse().resume(); } else { // This code is called if we startAsync and complete in the service() thread. // So instead of resuming the suspendedContext (which will finish the response processing), // we just have to mark the context as resumed like it has never been suspended. - final SuspendedContextImpl suspendContext = (SuspendedContextImpl) coyoteRequest.getResponse().getSuspendContext(); + final SuspendedContextImpl suspendContext = (SuspendedContextImpl) grizzlyRequest.getResponse().getSuspendContext(); suspendContext.markResumed(); suspendContext.getSuspendStatus().reset(); @@ -3587,21 +3582,21 @@ void onExitService() { asyncContextImpl.setOkToConfigure(false); if (asyncStarted.get()) { - coyoteRequest.getResponse().getSuspendContext().setTimeout(asyncContextImpl.getTimeout(), TimeUnit.MILLISECONDS); + grizzlyRequest.getResponse().getSuspendContext().setTimeout(asyncContextImpl.getTimeout(), TimeUnit.MILLISECONDS); } asyncContextImpl.onExitService(); } afterService = true; if (resume) { - coyoteRequest.getResponse().resume(); + grizzlyRequest.getResponse().resume(); } } void resumeAfterService() { if (afterService) { - coyoteRequest.getResponse().resume(); + grizzlyRequest.getResponse().resume(); } else { resume = true; } @@ -3708,20 +3703,20 @@ private void log(String message, Throwable t) { } private void populateSSLAttributes() { - RequestUtils.populateSSLAttributes(coyoteRequest); - Object attr = coyoteRequest.getAttribute(CERTIFICATES_ATTR); + RequestUtils.populateSSLAttributes(grizzlyRequest); + Object attr = grizzlyRequest.getAttribute(CERTIFICATES_ATTR); if (attr != null) { attributes.put(CERTIFICATES_ATTR, attr); } - attr = coyoteRequest.getAttribute(CIPHER_SUITE_ATTR); + attr = grizzlyRequest.getAttribute(CIPHER_SUITE_ATTR); if (attr != null) { attributes.put(CIPHER_SUITE_ATTR, attr); } - attr = coyoteRequest.getAttribute(KEY_SIZE_ATTR); + attr = grizzlyRequest.getAttribute(KEY_SIZE_ATTR); if (attr != null) { attributes.put(KEY_SIZE_ATTR, attr); } - attr = coyoteRequest.getAttribute(SSL_SESSION_ID_ATTR); + attr = grizzlyRequest.getAttribute(SSL_SESSION_ID_ATTR); if (attr != null) { attributes.put(SSL_SESSION_ID_ATTR, attr); } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationPushBuilder.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationPushBuilder.java index ce8429fbe63..b8c6d96c35a 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationPushBuilder.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationPushBuilder.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 2017-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -104,7 +105,7 @@ public ApplicationPushBuilder(HttpServletRequest request) { } if (current instanceof Request) { catalinaRequest = ((Request) current); - coyoteRequest = catalinaRequest.getCoyoteRequest(); + coyoteRequest = catalinaRequest.getGrizzlyRequest(); } else { String msg = MessageFormat.format( rb.getString(LogFacade.NO_PUSH_COYOTE_REQUEST_EXCEPTION), current.getClass().getName()); diff --git a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/VirtualServer.java b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/VirtualServer.java index 76d61c47744..1c9e96be06e 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/VirtualServer.java +++ b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/VirtualServer.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation. * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,41 +17,74 @@ package com.sun.enterprise.web; -import com.sun.enterprise.config.serverbeans.ApplicationRef; -import com.sun.enterprise.config.serverbeans.Applications; -import com.sun.enterprise.config.serverbeans.AuthRealm; -import com.sun.enterprise.config.serverbeans.Config; -import com.sun.enterprise.config.serverbeans.ConfigBeansUtilities; -import com.sun.enterprise.config.serverbeans.Domain; -import com.sun.enterprise.config.serverbeans.HttpService; -import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.config.serverbeans.ServerTags; -import com.sun.enterprise.deploy.shared.ArchiveFactory; -import com.sun.enterprise.deployment.Application; -import com.sun.enterprise.security.web.GlassFishSingleSignOn; -import com.sun.enterprise.server.logging.GFFileHandler; -import com.sun.enterprise.util.StringUtils; -import com.sun.enterprise.v3.common.PlainTextActionReporter; -import com.sun.enterprise.v3.services.impl.GrizzlyProxy; -import com.sun.enterprise.v3.services.impl.GrizzlyService; -import com.sun.enterprise.web.logger.CatalinaLogger; -import com.sun.enterprise.web.logger.FileLoggerHandler; -import com.sun.enterprise.web.logger.FileLoggerHandlerFactory; -import com.sun.enterprise.web.pluggable.WebContainerFeatureFactory; -import com.sun.enterprise.web.session.SessionCookieConfig; -import com.sun.web.security.RealmAdapter; +import static com.sun.enterprise.web.Constants.DEFAULT_WEB_MODULE_NAME; +import static com.sun.enterprise.web.Constants.ERROR_REPORT_VALVE; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; +import static org.glassfish.api.web.Constants.ADMIN_VS; +import static org.glassfish.web.LogFacade.ALLOW_ACCESS; +import static org.glassfish.web.LogFacade.CODE_FILTERS_NULL; +import static org.glassfish.web.LogFacade.DENY_ACCESS; +import static org.glassfish.web.LogFacade.ENABLE_SSO; +import static org.glassfish.web.LogFacade.IGNORE_INVALID_REALM; +import static org.glassfish.web.LogFacade.INVALID_AUTH_REALM; +import static org.glassfish.web.LogFacade.INVALID_LISTENER_VIRTUAL_SERVER; +import static org.glassfish.web.LogFacade.MODIFYING_WEB_XML; +import static org.glassfish.web.LogFacade.NOT_A_VALVE; +import static org.glassfish.web.LogFacade.NULL_VIRTUAL_SERVER_PROPERTY; +import static org.glassfish.web.LogFacade.REDIRECT_BOTH_URL_AND_URL_PREFIX; +import static org.glassfish.web.LogFacade.REDIRECT_MISSING_URL_OR_URL_PREFIX; +import static org.glassfish.web.LogFacade.REDIRECT_MULTIPLE_ELEMENT; +import static org.glassfish.web.LogFacade.SEND_ERROR_MULTIPLE_ELEMENT; +import static org.glassfish.web.LogFacade.SSO_MAX_INACTIVE_SET; +import static org.glassfish.web.LogFacade.SSO_REAP_INTERVAL_SET; +import static org.glassfish.web.LogFacade.UNABLE_RECONFIGURE_ACCESS_LOG; +import static org.glassfish.web.LogFacade.UNABLE_TO_LOAD_EXTENSION_SEVERE; +import static org.glassfish.web.LogFacade.VS_DEFAULT_WEB_MODULE; +import static org.glassfish.web.LogFacade.VS_DEFAULT_WEB_MODULE_DISABLED; -import org.apache.catalina.*; +import java.io.File; +import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.logging.Handler; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.catalina.Container; +import org.apache.catalina.ContainerListener; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.Pipeline; +import org.apache.catalina.Realm; +import org.apache.catalina.Valve; import org.apache.catalina.authenticator.AuthenticatorBase; import org.apache.catalina.authenticator.SingleSignOn; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardHost; -import org.apache.catalina.connector.Response; -import org.apache.catalina.connector.Request; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.valves.RemoteAddrValve; import org.apache.catalina.valves.RemoteHostValve; - import org.glassfish.api.ActionReport; import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.api.deployment.DeployCommandParameters; @@ -61,10 +95,9 @@ import org.glassfish.deployment.common.ApplicationConfigInfo; import org.glassfish.deployment.common.DeploymentContextImpl; import org.glassfish.deployment.common.DeploymentUtils; -import org.glassfish.embeddable.CommandRunner; import org.glassfish.embeddable.GlassFishException; -import org.glassfish.embeddable.web.Context; import org.glassfish.embeddable.web.ConfigException; +import org.glassfish.embeddable.web.Context; import org.glassfish.embeddable.web.WebListener; import org.glassfish.embeddable.web.config.VirtualServerConfig; import org.glassfish.grizzly.Buffer; @@ -72,77 +105,71 @@ import org.glassfish.grizzly.ConnectionProbe; import org.glassfish.grizzly.config.GenericGrizzlyListener; import org.glassfish.grizzly.config.dom.NetworkListener; -import org.glassfish.grizzly.http.ContentEncoding; -import org.glassfish.grizzly.http.HttpContent; +import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.grizzly.http.HttpCodecFilter; -import org.glassfish.grizzly.http.HttpProbe; -import org.glassfish.grizzly.http.HttpHeader; import org.glassfish.grizzly.http.HttpPacket; +import org.glassfish.grizzly.http.HttpProbe; import org.glassfish.grizzly.http.HttpRequestPacket; import org.glassfish.grizzly.http.HttpResponsePacket; -import org.glassfish.grizzly.http.TransferEncoding; import org.glassfish.grizzly.http.util.HttpStatus; -import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.hk2.api.ServiceLocator; -import org.glassfish.hk2.api.ServiceLocatorFactory; -import org.glassfish.web.LogFacade; -import org.glassfish.web.admin.monitor.RequestProbeProvider; -import org.glassfish.web.deployment.archivist.WebArchivist; -import org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl; - import org.glassfish.internal.api.ClassLoaderHierarchy; -import org.glassfish.internal.api.ServerContext; import org.glassfish.internal.api.Globals; +import org.glassfish.internal.api.ServerContext; import org.glassfish.internal.data.ApplicationInfo; import org.glassfish.internal.data.ApplicationRegistry; import org.glassfish.internal.deployment.Deployment; import org.glassfish.internal.deployment.ExtendedDeploymentContext; +import org.glassfish.web.LogFacade; +import org.glassfish.web.admin.monitor.RequestProbeProvider; +import org.glassfish.web.deployment.archivist.WebArchivist; +import org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl; import org.glassfish.web.loader.WebappClassLoader; import org.glassfish.web.valve.GlassFishValve; - import org.jvnet.hk2.config.Transaction; import org.jvnet.hk2.config.TransactionFailure; import org.jvnet.hk2.config.types.Property; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; -import java.io.File; -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; -import java.util.logging.LogRecord; +import com.sun.enterprise.config.serverbeans.ApplicationRef; +import com.sun.enterprise.config.serverbeans.Applications; +import com.sun.enterprise.config.serverbeans.AuthRealm; +import com.sun.enterprise.config.serverbeans.Config; +import com.sun.enterprise.config.serverbeans.ConfigBeansUtilities; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.HttpService; +import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.config.serverbeans.ServerTags; +import com.sun.enterprise.deploy.shared.ArchiveFactory; +import com.sun.enterprise.deployment.Application; +import com.sun.enterprise.security.web.GlassFishSingleSignOn; +import com.sun.enterprise.server.logging.GFFileHandler; +import com.sun.enterprise.util.StringUtils; +import com.sun.enterprise.v3.common.PlainTextActionReporter; +import com.sun.enterprise.v3.services.impl.GrizzlyProxy; +import com.sun.enterprise.v3.services.impl.GrizzlyService; +import com.sun.enterprise.web.logger.CatalinaLogger; +import com.sun.enterprise.web.logger.FileLoggerHandler; +import com.sun.enterprise.web.logger.FileLoggerHandlerFactory; +import com.sun.enterprise.web.pluggable.WebContainerFeatureFactory; +import com.sun.enterprise.web.session.SessionCookieConfig; +import com.sun.web.security.RealmAdapter; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.*; - /** - * Standard implementation of a virtual server (aka virtual host) in - * the iPlanet Application Server. + * Standard implementation of a virtual server (aka virtual host) in the iPlanet Application Server. */ -public class VirtualServer extends StandardHost - implements org.glassfish.embeddable.web.VirtualServer { +public class VirtualServer extends StandardHost implements org.glassfish.embeddable.web.VirtualServer { - private static final String STATE = "state"; - private static final String SSO_MAX_IDLE ="sso-max-inactive-seconds"; - private static final String SSO_REAP_INTERVAL ="sso-reap-interval-seconds"; - private static final String SSO_COOKIE_SECURE ="sso-cookie-secure"; + private static final String SSO_MAX_IDLE = "sso-max-inactive-seconds"; + private static final String SSO_REAP_INTERVAL = "sso-reap-interval-seconds"; private static final String DISABLED = "disabled"; - private static final String OFF = "off"; private static final String ON = "on"; /** @@ -155,12 +182,10 @@ public class VirtualServer extends StandardHost */ protected static final ResourceBundle rb = DEFAULT_LOGGER.getResourceBundle(); - // ------------------------------------------------------------ Constructor /** - * Default constructor that simply gets a handle to the web container - * subsystem's logger. + * Default constructor that simply gets a handle to the web container subsystem's logger. */ public VirtualServer() { origPipeline = pipeline; @@ -172,27 +197,24 @@ public VirtualServer() { // ----------------------------------------------------- Instance Variables /* - * The custom pipeline of this VirtualServer, which implements the - * following virtual server features: + * The custom pipeline of this VirtualServer, which implements the following virtual server features: * - * - state (disabled/off) - * - redirects + * - state (disabled/off) - redirects */ private VirtualServerPipeline vsPipeline; /* * The original (standard) pipeline of this VirtualServer. * - * Only one (custom or original) pipeline may be active at any given time. - * Any updates (such as adding or removing valves) to the currently - * active pipeline are propagated to the other. + * Only one (custom or original) pipeline may be active at any given time. Any updates (such as adding or removing + * valves) to the currently active pipeline are propagated to the other. */ private Pipeline origPipeline; /** * The id of this virtual server as specified in the configuration. */ - private String _id = null; + private String _id; /** * The logger to use for logging this virtual server @@ -202,8 +224,7 @@ public VirtualServer() { /** * The descriptive information about this implementation. */ - private static final String _info = - "com.sun.enterprise.web.VirtualServer/1.0"; + private static final String _info = "com.sun.enterprise.web.VirtualServer/1.0"; /** * The config bean associated with this VirtualServer @@ -216,16 +237,14 @@ public VirtualServer() { private MimeMap mimeMap; /* - * Indicates whether symbolic links from this virtual server's docroot - * are followed. This setting is inherited by all web modules deployed on - * this virtual server, unless overridden by a web modules allowLinking - * property in sun-web.xml. + * Indicates whether symbolic links from this virtual server's docroot are followed. This setting is inherited by all + * web modules deployed on this virtual server, unless overridden by a web modules allowLinking property in sun-web.xml. */ - private boolean allowLinking = false; + private boolean allowLinking; private String[] cacheControls; - private ClassLoaderHierarchy clh; + private ClassLoaderHierarchy classLoaderHierarchy; private Domain domain; @@ -239,19 +258,17 @@ public VirtualServer() { /* * The accesslog valve of this VirtualServer. * - * This valve is activated, that is, added to this virtual server's - * pipeline, only when access logging has been enabled. When acess logging - * has been disabled, this valve is removed from this virtual server's - * pipeline. + * This valve is activated, that is, added to this virtual server's pipeline, only when access logging has been enabled. + * When acess logging has been disabled, this valve is removed from this virtual server's pipeline. */ private PEAccessLogValve accessLogValve; // The value of the ssoCookieSecure property - private String ssoCookieSecure = null; + private String ssoCookieSecure; - private boolean ssoCookieHttpOnly = false; + private boolean ssoCookieHttpOnly; - private String defaultContextPath = null; + private String defaultContextPath; private ServerContext serverContext; @@ -261,23 +278,28 @@ public VirtualServer() { private WebContainer webContainer; - private boolean ssoFailoverEnabled = false; + private boolean ssoFailoverEnabled; + + private volatile FileLoggerHandler fileLoggerHandler; - private volatile FileLoggerHandler fileLoggerHandler = null; + private volatile FileLoggerHandlerFactory fileLoggerHandlerFactory; - private volatile FileLoggerHandlerFactory fileLoggerHandlerFactory = null; + private Deployment deployment; - private Deployment deployment = null; + private ArchiveFactory factory; - private ArchiveFactory factory = null; + private ActionReport report; + + private VirtualServerConfig config; - private ActionReport report = null; + private List listeners = new ArrayList<>(); // ------------------------------------------------------------- Properties /** * Return the virtual server identifier. */ + @Override public String getID() { return _id; } @@ -287,6 +309,7 @@ public String getID() { * * @param id New identifier for this virtual server */ + @Override public void setID(String id) { _id = id; } @@ -311,21 +334,19 @@ public void setIsActive(boolean isActive) { /** * Gets the value of the allowLinking property of this virtual server. * - * @return true if symbolic links from this virtual server's docroot (as - * well as symbolic links from archives of web modules deployed on this - * virtual server) are followed, false otherwise + * @return true if symbolic links from this virtual server's docroot (as well as symbolic links from archives of web + * modules deployed on this virtual server) are followed, false otherwise */ public boolean getAllowLinking() { return allowLinking; } /** - * Sets the allowLinking property of this virtual server, which determines - * whether symblic links from this virtual server's docroot are followed. + * Sets the allowLinking property of this virtual server, which determines whether symblic links from this virtual + * server's docroot are followed. * - * This property is inherited by all web modules deployed on this virtual - * server, unless overridden by the allowLinking property in a web module's - * sun-web.xml. + * This property is inherited by all web modules deployed on this virtual server, unless overridden by the allowLinking + * property in a web module's sun-web.xml. * * @param allowLinking Value of allowLinking property */ @@ -336,37 +357,36 @@ public void setAllowLinking(boolean allowLinking) { /** * Gets the config bean associated with this VirtualServer. */ - public com.sun.enterprise.config.serverbeans.VirtualServer getBean(){ + public com.sun.enterprise.config.serverbeans.VirtualServer getBean() { return vsBean; } /** * Sets the config bean for this VirtualServer */ - public void setBean( - com.sun.enterprise.config.serverbeans.VirtualServer vsBean){ + public void setBean(com.sun.enterprise.config.serverbeans.VirtualServer vsBean) { this.vsBean = vsBean; } /** * Gets the mime map associated with this VirtualServer. */ - public MimeMap getMimeMap(){ + public MimeMap getMimeMap() { return mimeMap; } /** * Sets the mime map for this VirtualServer */ - public void setMimeMap(MimeMap mimeMap){ + public void setMimeMap(MimeMap mimeMap) { this.mimeMap = mimeMap; } /** * Gets the Cache-Control configuration of this VirtualServer. * - * @return Cache-Control configuration of this VirtualServer, or null if - * no such configuration exists for this VirtualServer + * @return Cache-Control configuration of this VirtualServer, or null if no such configuration exists for this + * VirtualServer */ public String[] getCacheControls() { return cacheControls; @@ -375,8 +395,7 @@ public String[] getCacheControls() { /** * Sets the Cache-Control configuration for this VirtualServer * - * @param cacheControls Cache-Control configuration settings for this - * VirtualServer + * @param cacheControls Cache-Control configuration settings for this VirtualServer */ public void setCacheControls(String[] cacheControls) { this.cacheControls = cacheControls; @@ -386,6 +405,7 @@ public void setServices(ServiceLocator services) { this.services = services; } + @Override public String getInfo() { return _info; } @@ -399,7 +419,7 @@ public void setFileLoggerHandlerFactory(FileLoggerHandlerFactory factory) { } public void setClassLoaderHierarchy(ClassLoaderHierarchy clh) { - this.clh = clh; + this.classLoaderHierarchy = clh; } public void setDomain(Domain domain) { @@ -410,11 +430,10 @@ public void setDomain(Domain domain) { public Container findChild(String contextRoot) { if (defaultContextPath != null && "/".equals(contextRoot)) { return super.findChild(defaultContextPath); - } else { - return super.findChild(contextRoot); } - } + return super.findChild(contextRoot); + } // --------------------------------------------------------- Public Methods @@ -425,11 +444,9 @@ public Container findChild(String contextRoot) { * @param hreq the HttpServletRequest that has initiated the SSO session */ @Override - public void configureSingleSignOnCookieSecure(Cookie ssoCookie, - HttpServletRequest hreq) { + public void configureSingleSignOnCookieSecure(Cookie ssoCookie, HttpServletRequest hreq) { super.configureSingleSignOnCookieSecure(ssoCookie, hreq); - if (ssoCookieSecure != null && - !ssoCookieSecure.equals(SessionCookieConfig.DYNAMIC_SECURE)) { + if (ssoCookieSecure != null && !ssoCookieSecure.equals(SessionCookieConfig.DYNAMIC_SECURE)) { ssoCookie.setSecure(Boolean.parseBoolean(ssoCookieSecure)); } } @@ -439,13 +456,12 @@ public void configureSingleSignOnCookieHttpOnly(Cookie ssoCookie) { ssoCookie.setHttpOnly(ssoCookieHttpOnly); } - // ------------------------------------------------------ Lifecycle Methods /** - * Adds the given valve to the currently active pipeline, keeping the - * pipeline that is not currently active in sync. + * Adds the given valve to the currently active pipeline, keeping the pipeline that is not currently active in sync. */ + @Override public synchronized void addValve(GlassFishValve valve) { super.addValve(valve); if (pipeline == vsPipeline) { @@ -455,11 +471,11 @@ public synchronized void addValve(GlassFishValve valve) { } } - /** - * Adds the given Tomcat-style valve to the currently active pipeline, - * keeping the pipeline that is not currently active in sync. + * Adds the given Tomcat-style valve to the currently active pipeline, keeping the pipeline that is not currently active + * in sync. */ + @Override public synchronized void addValve(Valve valve) { super.addValve(valve); if (pipeline == vsPipeline) { @@ -469,11 +485,10 @@ public synchronized void addValve(Valve valve) { } } - /** - * Removes the given valve from the currently active pipeline, keeping the - * valve that is not currently active in sync. + * Removes the given valve from the currently active pipeline, keeping the valve that is not currently active in sync. */ + @Override public synchronized void removeValve(GlassFishValve valve) { super.removeValve(valve); if (pipeline == vsPipeline) { @@ -484,196 +499,173 @@ public synchronized void removeValve(GlassFishValve valve) { } private ConfigBeansUtilities getConfigBeansUtilities() { - if (services == null) return null; + if (services == null) { + return null; + } + return services.getService(ConfigBeansUtilities.class); } // ------------------------------------------------------ Protected Methods /** - * Gets the context root of the web module that the user/configuration - * has designated as the default-web-module for this virtual server. + * Gets the context root of the web module that the user/configuration has designated as the default-web-module for this + * virtual server. * - * The default-web-module for a virtual server is specified via the - * 'default-web-module' attribute of the 'virtual-server' element in - * server.xml. This is an optional attribute and if the configuration - * does not specify another web module (standalone or part of a - * j2ee-application) that is configured at a context-root="", then - * a default web module will be created and loaded. The value for this - * attribute is either "${standalone-web-module-name}" or + * The default-web-module for a virtual server is specified via the 'default-web-module' attribute of the + * 'virtual-server' element in server.xml. This is an optional attribute and if the configuration does not specify + * another web module (standalone or part of a j2ee-application) that is configured at a context-root="", then a default + * web module will be created and loaded. The value for this attribute is either "${standalone-web-module-name}" or * "${j2ee-app-name}:${web-module-uri}". * - * @return null if the default-web-module has not been specified or - * if the web module specified either could not be found or - * is disabled or does not specify this virtual server (if - * it specifies a value for the virtual-servers attribute) or - * if there was an error loading its deployment descriptors. + * @return null if the default-web-module has not been specified or if the web module specified either could not be + * found or is disabled or does not specify this virtual server (if it specifies a value for the virtual-servers + * attribute) or if there was an error loading its deployment descriptors. */ - protected String getDefaultContextPath(Domain domain, - ApplicationRegistry appRegistry) { - + protected String getDefaultContextPath(Domain domain, ApplicationRegistry appRegistry) { String contextRoot = null; - String wmID = getDefaultWebModuleID(); + String webModuleID = getDefaultWebModuleID(); - if (wmID != null) { - // Check if the default-web-module is part of a - // j2ee-application + if (webModuleID != null) { + // Check if the default-web-module is part of a Jakarta EE application Applications appsBean = domain.getApplications(); - WebModuleConfig wmInfo = findWebModuleInJ2eeApp(appsBean, wmID, - appRegistry); + WebModuleConfig wmInfo = findWebModuleInJ2eeApp(appsBean, webModuleID, appRegistry); if (wmInfo == null) { ConfigBeansUtilities cbu = getConfigBeansUtilities(); if (cbu == null) { contextRoot = null; - } - else { - contextRoot = cbu.getContextRoot(wmID); + } else { + contextRoot = cbu.getContextRoot(webModuleID); } } else { contextRoot = wmInfo.getContextPath(); } if (contextRoot == null) { - Object[] params = { wmID, getID() }; - _logger.log(Level.SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_NOT_FOUND, params); + Object[] params = { webModuleID, getID() }; + _logger.log(SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_NOT_FOUND, params); } } return contextRoot; } - protected WebModuleConfig getDefaultWebModule(Domain domain, - WebArchivist webArchivist, ApplicationRegistry appRegistry) { + protected WebModuleConfig getDefaultWebModule(Domain domain, WebArchivist webArchivist, ApplicationRegistry appRegistry) { + WebModuleConfig webModuleConfig = null; - WebModuleConfig wmInfo = null; - - String wmID = getDefaultWebModuleID(); - if (wmID != null) { - // Check if the default-web-module is part of a - // j2ee-application + String webModuleID = getDefaultWebModuleID(); + if (webModuleID != null) { + // Check if the default-web-module is part of a Jakarta EE application Applications appsBean = domain.getApplications(); - wmInfo = findWebModuleInJ2eeApp(appsBean, wmID, appRegistry); - if (wmInfo == null) { + webModuleConfig = findWebModuleInJ2eeApp(appsBean, webModuleID, appRegistry); + if (webModuleConfig == null) { ConfigBeansUtilities cbu = getConfigBeansUtilities(); String contextRoot = null; String location = null; if (cbu != null) { - contextRoot = cbu.getContextRoot(wmID); - location = cbu.getLocation(wmID); + contextRoot = cbu.getContextRoot(webModuleID); + location = cbu.getLocation(webModuleID); } - if (contextRoot!=null && location != null) { + if (contextRoot != null && location != null) { File docroot = new File(location); - WebBundleDescriptorImpl wbd = webArchivist.getDefaultWebXmlBundleDescriptor(); - wmInfo = new WebModuleConfig(); - wbd.setName(Constants.DEFAULT_WEB_MODULE_NAME); - wbd.setContextRoot(contextRoot); - wmInfo.setLocation(docroot); - wmInfo.setDescriptor(wbd); - wmInfo.setParentLoader(EmbeddedWebContainer.class.getClassLoader()); + WebBundleDescriptorImpl webBundleDescriptor = webArchivist.getDefaultWebXmlBundleDescriptor(); + webModuleConfig = new WebModuleConfig(); + webBundleDescriptor.setName(DEFAULT_WEB_MODULE_NAME); + webBundleDescriptor.setContextRoot(contextRoot); + webModuleConfig.setLocation(docroot); + webModuleConfig.setDescriptor(webBundleDescriptor); + webModuleConfig.setParentLoader(EmbeddedWebContainer.class.getClassLoader()); WebappClassLoader cloader = AccessController.doPrivileged(new PrivilegedAction() { @Override public WebappClassLoader run() { return new WebappClassLoader(EmbeddedWebContainer.class.getClassLoader()); } }); - wmInfo.setAppClassLoader(cloader); + webModuleConfig.setAppClassLoader(cloader); } } - if (wmInfo == null) { - _logger.log(Level.SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_NOT_FOUND, new Object[] {wmID, getID()}); + if (webModuleConfig == null) { + _logger.log(SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_NOT_FOUND, new Object[] { webModuleID, getID() }); } } - return wmInfo; + return webModuleConfig; } - /** - * If a default web module has not yet been configured and added to this - * virtual server's list of web modules then return the configuration - * information needed in order to create a default web module for this - * virtual server. + * If a default web module has not yet been configured and added to this virtual server's list of web modules then + * return the configuration information needed in order to create a default web module for this virtual server. * - * This method should be invoked only after all the standalone modules - * and the modules within j2ee-application elements have been added to - * this virtual server's list of modules (only then will one know whether - * the user has already configured a default web module or not). + * This method should be invoked only after all the standalone modules and the modules within j2ee-application elements + * have been added to this virtual server's list of modules (only then will one know whether the user has already + * configured a default web module or not). */ - public WebModuleConfig createSystemDefaultWebModuleIfNecessary( - WebArchivist webArchivist) { - - WebModuleConfig wmInfo = null; + public WebModuleConfig createSystemDefaultWebModuleIfNecessary(WebArchivist webArchivist) { + WebModuleConfig webModuleConfig = null; // Add a default context only if one hasn't already been loaded // and then too only if docroot is not null // String docroot = getAppBase(); - if (getDefaultWebModuleID() == null && findChild("") == null - && docroot != null) { - - WebBundleDescriptorImpl wbd = - webArchivist.getDefaultWebXmlBundleDescriptor(); - wmInfo = new WebModuleConfig(); - wbd.setModuleID(Constants.DEFAULT_WEB_MODULE_NAME); - wbd.setContextRoot(""); - wmInfo.setLocation(new File(docroot)); - wmInfo.setDescriptor(wbd); - wmInfo.setParentLoader( - serverContext.getCommonClassLoader()); + if (getDefaultWebModuleID() == null && findChild("") == null && docroot != null) { + + WebBundleDescriptorImpl webBundleDescriptor = webArchivist.getDefaultWebXmlBundleDescriptor(); + webModuleConfig = new WebModuleConfig(); + webBundleDescriptor.setModuleID(DEFAULT_WEB_MODULE_NAME); + webBundleDescriptor.setContextRoot(""); + webModuleConfig.setLocation(new File(docroot)); + webModuleConfig.setDescriptor(webBundleDescriptor); + webModuleConfig.setParentLoader(serverContext.getCommonClassLoader()); WebappClassLoader loader = AccessController.doPrivileged(new PrivilegedAction() { @Override public WebappClassLoader run() { return new WebappClassLoader(serverContext.getCommonClassLoader()); } }); + loader.start(); - wmInfo.setAppClassLoader(loader); - if ( wbd.getApplication() == null ) { + webModuleConfig.setAppClassLoader(loader); + + if (webBundleDescriptor.getApplication() == null) { Application application = Application.createApplication(); application.setVirtual(true); - application.setName(Constants.DEFAULT_WEB_MODULE_NAME); - wbd.setApplication(application); + application.setName(DEFAULT_WEB_MODULE_NAME); + webBundleDescriptor.setApplication(application); } } - return wmInfo; - + return webModuleConfig; } /** - * Returns the id of the default web module for this virtual server - * as specified in the 'default-web-module' attribute of the - * 'virtual-server' element. + * Returns the id of the default web module for this virtual server as specified in the 'default-web-module' attribute + * of the 'virtual-server' element. */ protected String getDefaultWebModuleID() { - String wmID = vsBean.getDefaultWebModule(); - if ("".equals(wmID)) { - wmID = null; + String webModuleID = vsBean.getDefaultWebModule(); + if ("".equals(webModuleID)) { + webModuleID = null; } - if (wmID != null && _logger.isLoggable(Level.FINE)) { - Object[] params = { wmID, _id }; - _logger.log(Level.FINE, LogFacade.VS_DEFAULT_WEB_MODULE, params); + + if (webModuleID != null && _logger.isLoggable(FINE)) { + Object[] params = { webModuleID, _id }; + _logger.log(FINE, VS_DEFAULT_WEB_MODULE, params); } - return wmID; + return webModuleID; } /** - * Finds and returns information about a web module embedded within a - * J2EE application, which is identified by a string of the form - * a:b or a#b, where a is the name - * of the J2EE application and b is the name of the embedded - * web module. + * Finds and returns information about a web module embedded within a J2EE application, which is identified by a string + * of the form a:b or a#b, where a is the name of the J2EE application and + * b is the name of the embedded web module. * - * @return null if id does not identify a web module embedded - * within a J2EE application. + * @return null if id does not identify a web module embedded within a J2EE application. */ - protected WebModuleConfig findWebModuleInJ2eeApp(Applications appsBean, - String id, ApplicationRegistry appRegistry) { - - WebModuleConfig wmInfo = null; + protected WebModuleConfig findWebModuleInJ2eeApp(Applications appsBean, String id, ApplicationRegistry appRegistry) { + WebModuleConfig webModuleConfig = null; // Check for ':' separator int separatorIndex = id.indexOf(Constants.NAME_SEPARATOR); @@ -686,13 +678,11 @@ protected WebModuleConfig findWebModuleInJ2eeApp(Applications appsBean, String moduleID = id.substring(separatorIndex + 1); com.sun.enterprise.config.serverbeans.Application appBean = - appsBean.getModule( - com.sun.enterprise.config.serverbeans.Application.class, appID); + appsBean.getModule(com.sun.enterprise.config.serverbeans.Application.class, appID); if ((appBean != null) && Boolean.valueOf(appBean.getEnabled())) { String location = appBean.getLocation(); - String moduleDir = DeploymentUtils.getRelativeEmbeddedModulePath( - location, moduleID); + String moduleDir = DeploymentUtils.getRelativeEmbeddedModulePath(location, moduleID); ApplicationInfo appInfo = appRegistry.get(appID); Application app = null; @@ -701,70 +691,62 @@ protected WebModuleConfig findWebModuleInJ2eeApp(Applications appsBean, } else { // XXX ApplicaionInfo is NULL after restart Object[] params = { id, getID() }; - _logger.log(Level.SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_DISABLED, - params); - return wmInfo; + _logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_DISABLED, params); + return webModuleConfig; } - WebBundleDescriptorImpl wbd = app.getModuleByTypeAndUri(WebBundleDescriptorImpl.class, moduleID); - String webUri = wbd.getModuleDescriptor().getArchiveUri(); - String contextRoot = wbd.getModuleDescriptor().getContextRoot(); + WebBundleDescriptorImpl webBundleDescriptor = app.getModuleByTypeAndUri(WebBundleDescriptorImpl.class, moduleID); + String webUri = webBundleDescriptor.getModuleDescriptor().getArchiveUri(); + String contextRoot = webBundleDescriptor.getModuleDescriptor().getContextRoot(); + if (moduleID.equals(webUri)) { StringBuilder dir = new StringBuilder(location); dir.append(File.separator); dir.append(moduleDir); File docroot = new File(dir.toString()); - wmInfo = new WebModuleConfig(); - wbd.setName(moduleID); - wbd.setContextRoot(contextRoot); - wmInfo.setDescriptor(wbd); - wmInfo.setLocation(docroot); - wmInfo.setParentLoader(EmbeddedWebContainer.class.getClassLoader()); + webModuleConfig = new WebModuleConfig(); + webBundleDescriptor.setName(moduleID); + webBundleDescriptor.setContextRoot(contextRoot); + webModuleConfig.setDescriptor(webBundleDescriptor); + webModuleConfig.setLocation(docroot); + webModuleConfig.setParentLoader(EmbeddedWebContainer.class.getClassLoader()); WebappClassLoader cloader = AccessController.doPrivileged(new PrivilegedAction() { @Override public WebappClassLoader run() { return new WebappClassLoader(EmbeddedWebContainer.class.getClassLoader()); } }); - wmInfo.setAppClassLoader(cloader); + webModuleConfig.setAppClassLoader(cloader); } } else { Object[] params = { id, getID() }; - _logger.log(Level.SEVERE, LogFacade.VS_DEFAULT_WEB_MODULE_DISABLED, - params); + _logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_DISABLED, params); } } - return wmInfo; + return webModuleConfig; } /** - * Virtual servers are maintained in the reference contained - * in Server element. First, we need to find the server - * and then get the virtual server from the correct reference + * Virtual servers are maintained in the reference contained in Server element. First, we need to find the server and + * then get the virtual server from the correct reference * * @param appName Name of the app to get vs * * @return virtual servers as a string (separated by space or comma) * - private String getVirtualServers(String appName) { - String ret = null; - Server server = Globals.getDefaultHabitat().forContract(Server.class).get(); - for (ApplicationRef appRef : server.getApplicationRef()) { - if (appRef.getRef().equals(appName)) { - return appRef.getVirtualServers(); - } - } - - return ret; - } */ - + * private String getVirtualServers(String appName) { String ret = null; Server server = + * Globals.getDefaultHabitat().forContract(Server.class).get(); for (ApplicationRef appRef : server.getApplicationRef()) + * { if (appRef.getRef().equals(appName)) { return appRef.getVirtualServers(); } } + * + * return ret; } + */ /** * Delete all aliases. */ - public void clearAliases(){ + public void clearAliases() { aliases = new String[0]; } @@ -815,14 +797,8 @@ List getProperties() { /** * Configures this virtual server. */ - public void configure( - String vsID, - com.sun.enterprise.config.serverbeans.VirtualServer vsBean, - String vsDocroot, - String vsLogFile, - MimeMap vsMimeMap, - String logServiceFile, - String logLevel) { + public void configure(String vsID, com.sun.enterprise.config.serverbeans.VirtualServer vsBean, String vsDocroot, String vsLogFile, + MimeMap vsMimeMap, String logServiceFile, String logLevel) { setDebug(debug); setAppBase(vsDocroot); setName(vsID); @@ -833,12 +809,12 @@ public void configure( String defaultContextXmlLocation = Constants.DEFAULT_CONTEXT_XML; String defaultWebXmlLocation = Constants.DEFAULT_WEB_XML; - //Begin EE: 4920692 Make the default-web.xml be relocatable + // Begin EE: 4920692 Make the default-web.xml be relocatable Property prop = vsBean.getProperty("default-web-xml"); if (prop != null) { defaultWebXmlLocation = prop.getValue(); } - //End EE: 4920692 Make the default-web.xml be relocatable + // End EE: 4920692 Make the default-web.xml be relocatable // allowLinking boolean allowLinking = false; @@ -872,8 +848,7 @@ public void configure( /** * Configures the valve_ and listener_ properties of this VirtualServer. */ - protected void configureCatalinaProperties(){ - + protected void configureCatalinaProperties() { List props = vsBean.getProperty(); if (props == null) { return; @@ -884,9 +859,7 @@ protected void configureCatalinaProperties(){ String propName = prop.getName(); String propValue = prop.getValue(); if (propName == null || propValue == null) { - _logger.log(Level.WARNING, - LogFacade.NULL_VIRTUAL_SERVER_PROPERTY, - getName()); + _logger.log(WARNING, NULL_VIRTUAL_SERVER_PROPERTY, getName()); } if (propName != null) { @@ -894,76 +867,34 @@ protected void configureCatalinaProperties(){ addValve(propValue); } else if (propName.startsWith("listener_")) { addListener(propValue); - } else if (propName.equals("securePagesWithPragma")){ + } else if (propName.equals("securePagesWithPragma")) { setSecurePagesWithPragma(Boolean.valueOf(propValue)); } } } } - /* * Configures this virtual server with the specified log file. * - * @param logFile The value of the virtual server's log-file attribute in - * the domain.xml + * @param logFile The value of the virtual server's log-file attribute in the domain.xml */ synchronized void setLogFile(String logFile, String logLevel, String logServiceFile) { - /** catalina file logger code - String logPrefix = logFile; - String logDir = null; - String logSuffix = null; - - if (logPrefix == null || logPrefix.equals("")) { - return; - } - - int index = logPrefix.lastIndexOf(File.separatorChar); - if (index != -1) { - logDir = logPrefix.substring(0, index); - logPrefix = logPrefix.substring(index+1); - } - - index = logPrefix.indexOf('.'); - if (index != -1) { - logSuffix = logPrefix.substring(index); - logPrefix = logPrefix.substring(0, index); - } - - logPrefix += "_"; - - FileLogger contextLogger = new FileLogger(); - if (logDir != null) { - contextLogger.setDirectory(logDir); - } - contextLogger.setPrefix(logPrefix); - if (logSuffix != null) { - contextLogger.setSuffix(logSuffix); - } - contextLogger.setTimestamp(true); - contextLogger.setLevel(logLevel); - */ - - /* - * Configure separate logger for this virtual server only if - * 'log-file' attribute of this and 'file' + * Configure separate logger for this virtual server only if 'log-file' attribute of this and 'file' * attribute of are different (See 6189219). */ - boolean noCustomLog = (logFile == null || - (logServiceFile != null && new File(logFile).equals( - new File(logServiceFile)))); + boolean noCustomLog = (logFile == null || (logServiceFile != null && new File(logFile).equals(new File(logServiceFile)))); - if ((fileLoggerHandler == null && noCustomLog) || - (fileLoggerHandler != null && logFile != null && - logFile.equals(fileLoggerHandler.getLogFile()))) { + if ((fileLoggerHandler == null && noCustomLog) + || (fileLoggerHandler != null && logFile != null && logFile.equals(fileLoggerHandler.getLogFile()))) { return; } Logger newLogger = null; FileLoggerHandler oldHandler = fileLoggerHandler; - //remove old handler + // remove old handler if (oldHandler != null) { _logger.removeHandler(oldHandler); } @@ -986,7 +917,7 @@ public void log(LogRecord record) { record.setResourceBundle(bundle); } } - record.setThreadID((int)Thread.currentThread().getId()); + record.setThreadID((int) Thread.currentThread().getId()); super.log(record); } @@ -1000,7 +931,7 @@ public ResourceBundle getResourceBundle() { public synchronized void addHandler(Handler handler) { super.addHandler(handler); if (handler instanceof FileLoggerHandler) { - ((FileLoggerHandler)handler).associate(); + ((FileLoggerHandler) handler).associate(); } } @@ -1021,13 +952,13 @@ public synchronized void removeHandler(Handler handler) { } if (hasHandler) { super.removeHandler(handler); - ((FileLoggerHandler)handler).disassociate(); + ((FileLoggerHandler) handler).disassociate(); } } } }; - synchronized(Logger.class) { + synchronized (Logger.class) { LogManager.getLogManager().addLogger(newLogger); } } @@ -1068,10 +999,9 @@ public synchronized void removeHandler(Handler handler) { */ void configureAliases() { List hosts = StringUtils.parseStringList(vsBean.getHosts(), ","); - for (int i=0; i < hosts.size(); i++ ){ - String alias = hosts.get(i).toString(); - if ( !alias.equalsIgnoreCase("localhost") && - !alias.equalsIgnoreCase("localhost.localdomain")){ + for (Object host : hosts) { + String alias = host.toString(); + if (!alias.equalsIgnoreCase("localhost") && !alias.equalsIgnoreCase("localhost.localdomain")) { addAlias(alias); } } @@ -1079,8 +1009,7 @@ void configureAliases() { void configureAliases(String... hosts) { for (String host : hosts) { - if ( !host.equalsIgnoreCase("localhost") && - !host.equalsIgnoreCase("localhost.localdomain")){ + if (!host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("localhost.localdomain")) { addAlias(host); } } @@ -1089,15 +1018,15 @@ void configureAliases(String... hosts) { /** * Configures this virtual server with its authentication realm. * - * Checks if this virtual server specifies any authRealm property, and - * if so, ensures that its value identifies a valid realm. + * Checks if this virtual server specifies any authRealm property, and if so, ensures that its value identifies a valid + * realm. * * @param securityService The security-service element from domain.xml */ void configureAuthRealm(SecurityService securityService) { List properties = vsBean.getProperty(); if (properties != null && properties.size() > 0) { - for (Property p: properties) { + for (Property p : properties) { if (p != null && "authRealm".equals(p.getName())) { authRealmName = p.getValue(); if (authRealmName != null) { @@ -1105,8 +1034,7 @@ void configureAuthRealm(SecurityService securityService) { List rs = securityService.getAuthRealm(); if (rs != null && rs.size() > 0) { for (AuthRealm r : rs) { - if (r != null && - r.getName().equals(authRealmName)) { + if (r != null && r.getName().equals(authRealmName)) { realm = r; break; } @@ -1114,8 +1042,7 @@ void configureAuthRealm(SecurityService securityService) { } if (realm == null) { - _logger.log(Level.SEVERE, LogFacade.INVALID_AUTH_REALM, - new Object[] {getID(), authRealmName}); + _logger.log(SEVERE, INVALID_AUTH_REALM, new Object[] { getID(), authRealmName }); } } break; @@ -1127,16 +1054,15 @@ void configureAuthRealm(SecurityService securityService) { /** * Gets the value of the authRealm property of this virtual server. * - * @return The value of the authRealm property of this virtual server, - * or null of this virtual server does not have any such property + * @return The value of the authRealm property of this virtual server, or null of this virtual server does not have any + * such property */ String getAuthRealmName() { return authRealmName; } /** - * Adds the Valve with the given class name to this - * VirtualServer. + * Adds the Valve with the given class name to this VirtualServer. * * @param valveName The valve's fully qualified class nam */ @@ -1147,44 +1073,46 @@ protected void addValve(String valveName) { } else if (valve instanceof GlassFishValve) { addValve((GlassFishValve) valve); } else { - _logger.log(Level.WARNING, LogFacade.NOT_A_VALVE, valveName); + _logger.log(WARNING, NOT_A_VALVE, valveName); } } /** - * Adds the Catalina listener with the given class name to this - * VirtualServer. + * Adds the Catalina listener with the given class name to this VirtualServer. * * @param listenerName The fully qualified class name of the listener */ protected void addListener(String listenerName) { Object listener = safeLoadInstance(listenerName); - - if ( listener == null ) return; + if (listener == null) { + return; + } if (listener instanceof ContainerListener) { - addContainerListener((ContainerListener)listener); - } else if (listener instanceof LifecycleListener){ - addLifecycleListener((LifecycleListener)listener); + addContainerListener((ContainerListener) listener); + } else if (listener instanceof LifecycleListener) { + addLifecycleListener((LifecycleListener) listener); } else { - _logger.log(Level.SEVERE, LogFacade.INVALID_LISTENER_VIRTUAL_SERVER, - new Object[] {listenerName, getID()}); + _logger.log(SEVERE, INVALID_LISTENER_VIRTUAL_SERVER, new Object[] { listenerName, getID() }); } } @Override protected Object loadInstance(String className) throws Exception { // See IT 11674 for why CommonClassLoader must be used - Class clazz = serverContext.getCommonClassLoader().loadClass(className); - return clazz.newInstance(); + return serverContext.getCommonClassLoader() + .loadClass(className) + .getDeclaredConstructor() + .newInstance(); } - private Object safeLoadInstance(String className){ - try{ + private Object safeLoadInstance(String className) { + try { return loadInstance(className); - } catch (Throwable ex){ - _logger.log(Level.SEVERE, LogFacade.UNABLE_TO_LOAD_EXTENSION_SEVERE, ex); + } catch (Throwable ex) { + _logger.log(SEVERE, UNABLE_TO_LOAD_EXTENSION_SEVERE, ex); } + return null; } @@ -1192,7 +1120,6 @@ private Object safeLoadInstance(String className){ * Configures this VirtualServer with its send-error properties. */ void configureErrorPage() { - ErrorPage errorPage = null; List props = vsBean.getProperty(); @@ -1204,9 +1131,7 @@ void configureErrorPage() { String propName = prop.getName(); String propValue = prop.getValue(); if (propName == null || propValue == null) { - _logger.log(Level.WARNING, - LogFacade.NULL_VIRTUAL_SERVER_PROPERTY, - getID()); + _logger.log(WARNING, NULL_VIRTUAL_SERVER_PROPERTY, getID()); continue; } @@ -1222,38 +1147,32 @@ void configureErrorPage() { String status = null; String[] errorParams = propValue.split(" "); - for (int j=0; j props = vsBean.getProperty(); @@ -1283,9 +1201,7 @@ void configureRedirect() { String propName = prop.getName(); String propValue = prop.getValue(); if (propName == null || propValue == null) { - _logger.log(Level.WARNING, - LogFacade.NULL_VIRTUAL_SERVER_PROPERTY, - getID()); + _logger.log(WARNING, NULL_VIRTUAL_SERVER_PROPERTY, getID()); continue; } @@ -1302,64 +1218,47 @@ void configureRedirect() { String escape = null; String[] redirectParams = propValue.split(" "); - for (int j=0; j 0 - && urlPrefix != null && urlPrefix.length() > 0) { - _logger.log(Level.WARNING, - LogFacade.REDIRECT_BOTH_URL_AND_URL_PREFIX, - new Object[] { propValue, getID() }); + if (url != null && url.length() > 0 && urlPrefix != null && urlPrefix.length() > 0) { + _logger.log(WARNING, REDIRECT_BOTH_URL_AND_URL_PREFIX, new Object[] { propValue, getID() }); } boolean escapeURI = true; @@ -1369,9 +1268,7 @@ void configureRedirect() { } else if ("no".equalsIgnoreCase(escape)) { escapeURI = false; } else { - _logger.log(Level.WARNING, - LogFacade.REDIRECT_INVALID_ESCAPE, - new Object[] { propValue, getID() }); + _logger.log(WARNING, LogFacade.REDIRECT_INVALID_ESCAPE, new Object[] { propValue, getID() }); } } @@ -1391,23 +1288,19 @@ void configureRedirect() { /** * Configures the SSO valve of this VirtualServer. */ - void configureSingleSignOn(boolean globalSSOEnabled, - WebContainerFeatureFactory webContainerFeatureFactory, - boolean ssoFailoverEnabled) { - - + void configureSingleSignOn(boolean globalSSOEnabled, WebContainerFeatureFactory webContainerFeatureFactory, boolean ssoFailoverEnabled) { if (!isSSOEnabled(globalSSOEnabled)) { /* * Disable SSO */ - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.DISABLE_SSO, getID()); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, LogFacade.DISABLE_SSO, getID()); } boolean hasExistingSSO = false; // Remove existing SSO valve (if any) GlassFishValve[] valves = getValves(); - for (int i=0; valves!=null && i values = StringUtils.parseStringList(cacheControl, ","); if (values != null && !values.isEmpty()) { @@ -1807,17 +1675,17 @@ private boolean isSSOEnabled(boolean globalSSOEnabled) { if (vsBean != null) { ssoEnabled = vsBean.getSsoEnabled(); } - return "inherit".equals(ssoEnabled) && globalSSOEnabled - || ConfigBeansUtilities.toBoolean(ssoEnabled); + + return "inherit".equals(ssoEnabled) && globalSSOEnabled || ConfigBeansUtilities.toBoolean(ssoEnabled); } private void setSingleSignOnForChildren(SingleSignOn sso) { for (Container container : findChildren()) { if (container instanceof StandardContext) { - StandardContext context = (StandardContext)container; - for (GlassFishValve valve: context.getValves()) { + StandardContext context = (StandardContext) container; + for (GlassFishValve valve : context.getValves()) { if (valve instanceof AuthenticatorBase) { - ((AuthenticatorBase)valve).setSingleSignOn(sso); + ((AuthenticatorBase) valve).setSingleSignOn(sso); break; } } @@ -1828,41 +1696,34 @@ private void setSingleSignOnForChildren(SingleSignOn sso) { /** * Determines whether access logging is enabled for this virtual server. * - * @param globalAccessLoggingEnabled The value of the - * accessLoggingEnabled property of the http-service element + * @param globalAccessLoggingEnabled The value of the accessLoggingEnabled property of the http-service element * - * @return true if access logging is enabled for this virtual server, - * false otherwise. + * @return true if access logging is enabled for this virtual server, false otherwise. */ boolean isAccessLoggingEnabled(boolean globalAccessLoggingEnabled) { String enabled = vsBean.getAccessLoggingEnabled(); - return "inherit".equals(enabled) && globalAccessLoggingEnabled || - ConfigBeansUtilities.toBoolean(enabled); + return "inherit".equals(enabled) && globalAccessLoggingEnabled || ConfigBeansUtilities.toBoolean(enabled); } @Override public void setRealm(Realm realm) { if ((realm != null) && !(realm instanceof RealmAdapter)) { - _logger.log(Level.SEVERE, LogFacade.IGNORE_INVALID_REALM, - new Object[] { realm.getClass().getName(), - RealmAdapter.class.getName()}); + _logger.log(SEVERE, IGNORE_INVALID_REALM, + new Object[] { realm.getClass().getName(), RealmAdapter.class.getName() }); } else { super.setRealm(realm); } } /** - * Configures the security level of the SSO cookie for this virtual - * server, based on the value of its sso-cookie-secure attribute + * Configures the security level of the SSO cookie for this virtual server, based on the value of its sso-cookie-secure + * attribute */ private void configureSingleSignOnCookieSecure() { String cookieSecure = vsBean.getSsoCookieSecure(); - if (!"true".equalsIgnoreCase(cookieSecure) && - !"false".equalsIgnoreCase(cookieSecure) && - !cookieSecure.equalsIgnoreCase( - SessionCookieConfig.DYNAMIC_SECURE)) { - _logger.log(Level.WARNING, LogFacade.INVALID_SSO_COOKIE_SECURE, - new Object[] {cookieSecure, getID()}); + if (!"true".equalsIgnoreCase(cookieSecure) && !"false".equalsIgnoreCase(cookieSecure) + && !cookieSecure.equalsIgnoreCase(SessionCookieConfig.DYNAMIC_SECURE)) { + _logger.log(WARNING, LogFacade.INVALID_SSO_COOKIE_SECURE, new Object[] { cookieSecure, getID() }); } else { ssoCookieSecure = cookieSecure; } @@ -1875,14 +1736,13 @@ private void configureSingleSignOnCookieHttpOnly() { /** * Configures the error report valve of this VirtualServer. * - *

The error report valve of a virtual server is specified through - * a property with name errorReportValve, whose value is the - * valve's fully qualified classname. A null or empty classname - * disables the error report valve and therefore the container's - * default error page mechanism for error responses. + *

+ * The error report valve of a virtual server is specified through a property with name errorReportValve, whose + * value is the valve's fully qualified classname. A null or empty classname disables the error report valve and + * therefore the container's default error page mechanism for error responses. */ void configureErrorReportValve() { - Property prop = vsBean.getProperty(Constants.ERROR_REPORT_VALVE); + Property prop = vsBean.getProperty(ERROR_REPORT_VALVE); if (prop != null) { setErrorReportValveClass(prop.getValue()); } @@ -1907,15 +1767,13 @@ void setWebContainer(WebContainer webContainer) { // ----------------------------------------------------- embedded methods - private VirtualServerConfig config; - - private List listeners = new ArrayList(); /** * Sets the docroot of this VirtualServer. * * @param docRoot the docroot of this VirtualServer. */ + @Override public void setDocRoot(File docRoot) { this.setAppBase(docRoot.getPath()); } @@ -1923,46 +1781,44 @@ public void setDocRoot(File docRoot) { /** * Gets the docroot of this VirtualServer. */ + @Override public File getDocRoot() { return new File(getAppBase()); } /** - * Sets the collection of WebListener instances from which - * this VirtualServer receives requests. + * Sets the collection of WebListener instances from which this VirtualServer receives requests. * - * @param webListeners the collection of WebListener instances from which - * this VirtualServer receives requests. + * @param webListeners the collection of WebListener instances from which this VirtualServer receives + * requests. */ - public void setWebListeners(WebListener... webListeners) { + public void setWebListeners(WebListener... webListeners) { if (webListeners != null) { listeners = Arrays.asList(webListeners); } } /** - * Gets the collection of WebListener instances from which - * this VirtualServer receives requests. + * Gets the collection of WebListener instances from which this VirtualServer receives requests. * - * @return the collection of WebListener instances from which - * this VirtualServer receives requests. + * @return the collection of WebListener instances from which this VirtualServer receives requests. */ + @Override public Collection getWebListeners() { return listeners; } /** - * Registers the given Context with this VirtualServer - * at the given context root. + * Registers the given Context with this VirtualServer at the given context root. * - *

If this VirtualServer has already been started, the - * given context will be started as well. + *

+ * If this VirtualServer has already been started, the given context will be started as well. */ - public void addContext(Context context, String contextRoot) - throws ConfigException, GlassFishException { + @Override + public void addContext(Context context, String contextRoot) throws ConfigException, GlassFishException { - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.VS_ADDED_CONTEXT); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, LogFacade.VS_ADDED_CONTEXT); } if (!(context instanceof ContextFacade)) { @@ -1971,21 +1827,23 @@ public void addContext(Context context, String contextRoot) } if (!contextRoot.startsWith("/")) { - contextRoot = "/"+contextRoot; + contextRoot = "/" + contextRoot; } ExtendedDeploymentContext deploymentContext = null; try { - if (factory==null) + if (factory == null) { factory = services.getService(ArchiveFactory.class); + } ContextFacade facade = (ContextFacade) context; File docRoot = facade.getDocRoot(); ClassLoader classLoader = facade.getClassLoader(); ReadableArchive archive = factory.openArchive(docRoot); - if (report==null) + if (report == null) { report = new PlainTextActionReporter(); + } ServerEnvironment env = services.getService(ServerEnvironment.class); @@ -1996,14 +1854,14 @@ public void addContext(Context context, String contextRoot) params.virtualservers = getName(); params.target = "server"; - ExtendedDeploymentContext initialContext = - new DeploymentContextImpl(report, archive, params, env); + ExtendedDeploymentContext initialContext = new DeploymentContextImpl(report, archive, params, env); - if (deployment==null) + if (deployment == null) { deployment = services.getService(Deployment.class); + } ArchiveHandler archiveHandler = deployment.getArchiveHandler(archive); - if (archiveHandler==null) { + if (archiveHandler == null) { throw new RuntimeException("Cannot find archive handler for source archive"); } @@ -2013,37 +1871,35 @@ public void addContext(Context context, String contextRoot) ApplicationInfo appInfo = deployment.get(params.name); ApplicationRef appRef = domain.getApplicationRefInServer(params.target, params.name); - if (appInfo!=null && appRef!=null) { + if (appInfo != null && appRef != null) { if (appRef.getVirtualServers().contains(getName())) { - throw new ConfigException( - "Context with name "+params.name+" is already registered on virtual server "+getName()); + throw new ConfigException("Context with name " + params.name + " is already registered on virtual server " + getName()); } else { String virtualServers = appRef.getVirtualServers(); - virtualServers = virtualServers + ","+getName(); + virtualServers = virtualServers + "," + getName(); params.virtualservers = virtualServers; params.force = Boolean.TRUE; - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "Virtual server "+getName()+" added to context "+params.name); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, "Virtual server " + getName() + " added to context " + params.name); } return; } } - deploymentContext = deployment.getBuilder( - _logger, params, report).source(archive).archiveHandler( - archiveHandler).build(initialContext); + deploymentContext = deployment.getBuilder(_logger, params, report).source(archive).archiveHandler(archiveHandler) + .build(initialContext); Properties properties = new Properties(); deploymentContext.getAppProps().putAll(properties); if (classLoader != null) { - ClassLoader parentCL = clh.createApplicationParentCL(classLoader, deploymentContext); + ClassLoader parentCL = classLoaderHierarchy.createApplicationParentCL(classLoader, deploymentContext); ClassLoader cl = archiveHandler.getClassLoader(parentCL, deploymentContext); deploymentContext.setClassLoader(cl); } - ApplicationConfigInfo savedAppConfig = - new ApplicationConfigInfo(apps.getModule(com.sun.enterprise.config.serverbeans.Application.class, params.name)); + ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo( + apps.getModule(com.sun.enterprise.config.serverbeans.Application.class, params.name)); Properties appProps = deploymentContext.getAppProps(); String appLocation = DeploymentUtils.relativizeWithinDomainIfPossible(deploymentContext.getSource().getURI()); @@ -2057,10 +1913,10 @@ public void addContext(Context context, String contextRoot) Transaction t = deployment.prepareAppConfigChanges(deploymentContext); appInfo = deployment.deploy(deploymentContext); - if (appInfo!=null) { + if (appInfo != null) { facade.setAppName(appInfo.getName()); - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.VS_ADDED_CONTEXT, new Object[]{getName(), appInfo.getName()}); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, LogFacade.VS_ADDED_CONTEXT, new Object[] { getName(), appInfo.getName() }); } deployment.registerAppInDomainXML(appInfo, deploymentContext, t); } else { @@ -2080,15 +1936,14 @@ public void addContext(Context context, String contextRoot) } updateWebXml(facade, file); } else { - _logger.log(Level.SEVERE, LogFacade.APP_NOT_FOUND); + _logger.log(SEVERE, LogFacade.APP_NOT_FOUND); } ReadableArchive source = appInfo.getSource(); UndeployCommandParameters undeployParams = new UndeployCommandParameters(params.name); undeployParams.origin = UndeployCommandParameters.Origin.undeploy; undeployParams.target = "server"; - ExtendedDeploymentContext undeploymentContext = - deployment.getBuilder(_logger, undeployParams, report).source(source).build(); + ExtendedDeploymentContext undeploymentContext = deployment.getBuilder(_logger, undeployParams, report).source(source).build(); deployment.undeploy(params.name, undeploymentContext); params.origin = DeployCommandParameters.Origin.load; @@ -2097,7 +1952,7 @@ public void addContext(Context context, String contextRoot) deploymentContext = deployment.getBuilder(_logger, params, report).source(archive).build(); if (classLoader != null) { - ClassLoader parentCL = clh.createApplicationParentCL(classLoader, deploymentContext); + ClassLoader parentCL = classLoaderHierarchy.createApplicationParentCL(classLoader, deploymentContext); archiveHandler = deployment.getArchiveHandler(archive); ClassLoader cl = archiveHandler.getClassLoader(parentCL, deploymentContext); deploymentContext.setClassLoader(cl); @@ -2109,15 +1964,15 @@ public void addContext(Context context, String contextRoot) // We can't use Deployment.enable since it doesn't take DeploymentContext with custom class loader deployment.updateAppEnabledAttributeInDomainXML(params.name, params.target, true); - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.VS_ENABLED_CONTEXT, new Object[]{getName(), params.name()}); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, LogFacade.VS_ENABLED_CONTEXT, new Object[] { getName(), params.name() }); } if (delete) { if (file != null) { if (file.exists() && !file.delete()) { String path = file.toString(); - _logger.log(Level.WARNING, LogFacade.UNABLE_TO_DELETE, path); + _logger.log(WARNING, LogFacade.UNABLE_TO_DELETE, path); } } } @@ -2133,7 +1988,7 @@ public void addContext(Context context, String contextRoot) wm.setDefaultWebXml(config.getDefaultWebXml()); } } else { - throw new ConfigException("Deployed app not found "+contextRoot); + throw new ConfigException("Deployed app not found " + contextRoot); } if (deploymentContext != null) { @@ -2141,7 +1996,7 @@ public void addContext(Context context, String contextRoot) } } catch (Exception ex) { - if (deployment!=null && deploymentContext!=null) { + if (deployment != null && deploymentContext != null) { deploymentContext.clean(); } throw new GlassFishException(ex); @@ -2150,15 +2005,15 @@ public void addContext(Context context, String contextRoot) } /** - * Stops the given context and removes it from this - * VirtualServer. + * Stops the given context and removes it from this VirtualServer. */ + @Override public void removeContext(Context context) throws GlassFishException { ActionReport report = services.getService(ActionReport.class, "plain"); Deployment deployment = services.getService(Deployment.class); String name; if (context instanceof ContextFacade) { - name = ((ContextFacade)context).getAppName(); + name = ((ContextFacade) context).getAppName(); } else { name = context.getPath(); } @@ -2188,62 +2043,59 @@ public void removeContext(Context context) throws GlassFishException { deployment.undeploy(name, deploymentContext); deployment.unregisterAppFromDomainXML(name, "server"); } catch (IOException e) { - _logger.log(Level.SEVERE, LogFacade.REMOVE_CONTEXT_ERROR, e); + _logger.log(SEVERE, LogFacade.REMOVE_CONTEXT_ERROR, e); report.setActionExitCode(ActionReport.ExitCode.FAILURE); throw new GlassFishException("Cannot create context for undeployment ", e); } catch (TransactionFailure e) { throw new GlassFishException(e); } finally { - if (deploymentContext!=null) { + if (deploymentContext != null) { deploymentContext.clean(); } } - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.REMOVED_CONTEXT, name); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, LogFacade.REMOVED_CONTEXT, name); } } - /** * Finds the Context registered at the given context root. */ + @Override public Context getContext(String contextRoot) { if (!contextRoot.startsWith("/")) { - contextRoot = "/"+contextRoot; + contextRoot = "/" + contextRoot; } - return (Context)findChild(contextRoot); + return (Context) findChild(contextRoot); } /** - * Gets the collection of Context instances registered with - * this VirtualServer. + * Gets the collection of Context instances registered with this VirtualServer. */ + @Override public Collection getContexts() { - Collection ctxs = new ArrayList(); + Collection ctxs = new ArrayList<>(); for (Container container : findChildren()) { if (container instanceof Context) { - ctxs.add((Context)container); + ctxs.add((Context) container); } } return ctxs; } /** - * Reconfigures this VirtualServer with the given - * configuration. + * Reconfigures this VirtualServer with the given configuration. * - *

In order for the given configuration to take effect, this - * VirtualServer may be stopped and restarted. + *

+ * In order for the given configuration to take effect, this VirtualServer may be stopped and restarted. */ - public void setConfig(VirtualServerConfig config) - throws ConfigException { + @Override + public void setConfig(VirtualServerConfig config) throws ConfigException { this.config = config; configureSingleSignOn(config.isSsoEnabled(), - Globals.getDefaultHabitat().getService( - PEWebContainerFeatureFactoryImpl.class), - false); + Globals.getDefaultHabitat().getService(PEWebContainerFeatureFactoryImpl.class), false); if (config.isAccessLoggingEnabled()) { enableAccessLogging(); } else { @@ -2261,6 +2113,7 @@ public void setConfig(VirtualServerConfig config) /** * Gets the current configuration of this VirtualServer. */ + @Override public VirtualServerConfig getConfig() { return config; } @@ -2268,9 +2121,9 @@ public VirtualServerConfig getConfig() { @Override public synchronized void stop() throws LifecycleException { if (fileLoggerHandler != null) { - _logger.removeHandler(fileLoggerHandler); - close(fileLoggerHandler); - fileLoggerHandler = null; + _logger.removeHandler(fileLoggerHandler); + close(fileLoggerHandler); + fileLoggerHandler = null; } setLogger(_logger, "INFO"); @@ -2278,7 +2131,6 @@ public synchronized void stop() throws LifecycleException { } public void updateWebXml(ContextFacade facade, File file) throws Exception { - Map servlets = facade.getAddedServlets(); Map mappings = facade.getServletMappings(); List listeners = facade.getListeners(); @@ -2287,8 +2139,8 @@ public void updateWebXml(ContextFacade facade, File file) throws Exception { Map urlPatternFilterMappings = facade.getUrlPatternFilterMappings(); if (!filters.isEmpty() || !listeners.isEmpty() || !servlets.isEmpty()) { - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, LogFacade.MODIFYING_WEB_XML, file.getAbsolutePath()); + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, MODIFYING_WEB_XML, file.getAbsolutePath()); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); @@ -2317,12 +2169,11 @@ public void updateWebXml(ContextFacade facade, File file) throws Exception { // Update for (Map.Entry entry : filters.entrySet()) { NodeList filterList = doc.getElementsByTagName("filter-name"); - for (int i=0; i initParams = - facade.getFilterRegistration(entry.getKey().toString()).getInitParameters(); + Map initParams = facade.getFilterRegistration(entry.getKey().toString()).getInitParameters(); if ((initParams != null) && (!initParams.isEmpty())) { Element initParam = doc.createElement("init-param"); for (Map.Entry param : initParams.entrySet()) { @@ -2388,12 +2238,12 @@ public void updateWebXml(ContextFacade facade, File file) throws Exception { // Update for (Map.Entry entry : servlets.entrySet()) { NodeList servletList = doc.getElementsByTagName("servlet-name"); - for (int i=0; i initParams = - facade.getServletRegistration(entry.getKey().toString()).getInitParameters(); + Map initParams = facade.getServletRegistration(entry.getKey().toString()).getInitParameters(); if ((initParams != null) && (!initParams.isEmpty())) { Element initParam = doc.createElement("init-param"); for (Map.Entry param : initParams.entrySet()) { @@ -2436,12 +2285,12 @@ public void updateWebXml(ContextFacade facade, File file) throws Exception { // Update for (Map.Entry mapping : mappings.entrySet()) { NodeList servletList = doc.getElementsByTagName("servlet-name"); - for (int i=0; i getGrizzlyNetworkListeners() { - List listenerList = StringUtils.parseStringList( - vsBean.getNetworkListeners(), ","); - String[] listeners = (listenerList != null) ? - listenerList.toArray(new String[listenerList.size()]) : - new String[0]; - List networkListeners = new ArrayList(); + List listenerList = StringUtils.parseStringList(vsBean.getNetworkListeners(), ","); + String[] listeners = (listenerList != null) ? listenerList.toArray(new String[listenerList.size()]) : new String[0]; + List networkListeners = new ArrayList<>(); for (String listener : listeners) { - for (NetworkListener networkListener : - serverConfig.getNetworkConfig().getNetworkListeners().getNetworkListener()) { + for (NetworkListener networkListener : serverConfig.getNetworkConfig().getNetworkListeners().getNetworkListener()) { if (networkListener.getName().equals(listener)) { networkListeners.add(networkListener); } @@ -2512,36 +2356,34 @@ private List getHttpProbeImpl() { for (final NetworkListener listener : getGrizzlyNetworkListeners()) { final GrizzlyProxy proxy = (GrizzlyProxy) grizzlyService.lookupNetworkProxy(listener); if (proxy != null) { - GenericGrizzlyListener grizzlyListener = (GenericGrizzlyListener) proxy.getUnderlyingListener(); - List codecFilters = grizzlyListener.getFilters(HttpCodecFilter.class); - if (codecFilters != null && !codecFilters.isEmpty()) { - for (HttpCodecFilter codecFilter : codecFilters) { - HttpProbe[] probes = codecFilter.getMonitoringConfig().getProbes(); - if (probes != null) { - for (HttpProbe probe : probes) { - if (probe instanceof HttpProbeImpl) { - httpProbes.add((HttpProbeImpl)probe); - } - } - } - } - } + GenericGrizzlyListener grizzlyListener = (GenericGrizzlyListener) proxy.getUnderlyingListener(); + List codecFilters = grizzlyListener.getFilters(HttpCodecFilter.class); + if (codecFilters != null && !codecFilters.isEmpty()) { + for (HttpCodecFilter codecFilter : codecFilters) { + HttpProbe[] probes = codecFilter.getMonitoringConfig().getProbes(); + if (probes != null) { + for (HttpProbe probe : probes) { + if (probe instanceof HttpProbeImpl) { + httpProbes.add((HttpProbeImpl) probe); + } + } + } + } + } } } return httpProbes; } - // ---------------------------------------------------------- Nested Classes - private final class HttpProbeImpl extends HttpProbe.Adapter { - boolean accessLoggingEnabled = false; - NetworkListener listener = null; + boolean accessLoggingEnabled; + NetworkListener listener; - public HttpProbeImpl(NetworkListener listener, boolean accessLoggingEnabled) { + public HttpProbeImpl(NetworkListener listener, boolean accessLoggingEnabled) { this.listener = listener; this.accessLoggingEnabled = accessLoggingEnabled; } @@ -2565,32 +2407,30 @@ public void onErrorEvent(Connection connection, HttpPacket packet, Throwable err // 400 should be hardcoded since the response status isn't available for bad requests responsePacket.setStatus(HttpStatus.BAD_REQUEST_400); - org.glassfish.grizzly.http.server.Request request = org.glassfish.grizzly.http.server.Request.create(); -// org.glassfish.grizzly.http.server.Response response = org.glassfish.grizzly.http.server.Response.create(); - org.glassfish.grizzly.http.server.Response response = request.getResponse(); + org.glassfish.grizzly.http.server.Request grizzlyRequest = org.glassfish.grizzly.http.server.Request.create(); + org.glassfish.grizzly.http.server.Response grizzlyResponse = grizzlyRequest.getResponse(); -// request.initialize(response, requestPacket, FilterChainContext.create(connection), null); - request.initialize(/*response,*/ requestPacket, FilterChainContext.create(connection), null); - response.initialize(request, responsePacket, FilterChainContext.create(connection), null, null); + grizzlyRequest.initialize(requestPacket, FilterChainContext.create(connection), null); + grizzlyResponse.initialize(grizzlyRequest, responsePacket, FilterChainContext.create(connection), null, null); - Response res = new Response(); - res.setCoyoteResponse(response); + Response catalinaResponse = new Response(); + catalinaResponse.setCoyoteResponse(grizzlyResponse); WebConnector connector = webContainer.getConnectorMap().get(listener.getName()); if (connector != null) { - Request req = new Request(); - req.setCoyoteRequest(request); - req.setConnector(connector); + Request catalinaRequest = new Request(); + catalinaRequest.setGrizzlyRequest(grizzlyRequest); + catalinaRequest.setConnector(connector); try { - accessLogValve.postInvoke(req, res); + accessLogValve.postInvoke(catalinaRequest, catalinaResponse); } catch (IOException ex) { - _logger.log(Level.SEVERE, LogFacade.UNABLE_RECONFIGURE_ACCESS_LOG, ex); + _logger.log(SEVERE, UNABLE_RECONFIGURE_ACCESS_LOG, ex); } } else { - _logger.log(Level.SEVERE, LogFacade.UNABLE_RECONFIGURE_ACCESS_LOG); + _logger.log(SEVERE, UNABLE_RECONFIGURE_ACCESS_LOG); } } else { - _logger.log(Level.SEVERE, LogFacade.UNABLE_RECONFIGURE_ACCESS_LOG); + _logger.log(SEVERE, UNABLE_RECONFIGURE_ACCESS_LOG); } } } @@ -2598,5 +2438,3 @@ public void onErrorEvent(Connection connection, HttpPacket packet, Throwable err } } - - From 66102878ae21e18311294224cc4a6d3aa9d7f7ff Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Mon, 11 Apr 2022 00:28:59 +0200 Subject: [PATCH 08/11] Integrate grizzly 4 m2 Signed-off-by: Arjan Tijms --- nucleus/parent/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nucleus/parent/pom.xml b/nucleus/parent/pom.xml index 6e4cf822390..ac84d559360 100644 --- a/nucleus/parent/pom.xml +++ b/nucleus/parent/pom.xml @@ -122,7 +122,7 @@ 4.2.4 - 4.0.0-M1 + 4.0.0-M2 2.0.0 3.2.3 4.1.2 From ba9cf4b652946c7958449187e82990a919ce8fbc Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Mon, 11 Apr 2022 00:29:28 +0200 Subject: [PATCH 09/11] Fix validation for session cookie config Signed-off-by: Arjan Tijms --- .../core/SessionCookieConfigImpl.java | 198 +++++++----------- 1 file changed, 81 insertions(+), 117 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/SessionCookieConfigImpl.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/SessionCookieConfigImpl.java index 5a6f8a9c49f..6aa6b396bb1 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/SessionCookieConfigImpl.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/SessionCookieConfigImpl.java @@ -17,22 +17,31 @@ package org.apache.catalina.core; -import org.apache.catalina.LogFacade; +import static java.lang.String.CASE_INSENSITIVE_ORDER; +import static java.util.Collections.unmodifiableMap; +import static org.apache.catalina.LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT; +import static org.apache.catalina.core.Constants.COOKIE_DOMAIN_ATTR; +import static org.apache.catalina.core.Constants.COOKIE_HTTP_ONLY_ATTR; +import static org.apache.catalina.core.Constants.COOKIE_MAX_AGE_ATTR; +import static org.apache.catalina.core.Constants.COOKIE_PATH_ATTR; +import static org.apache.catalina.core.Constants.COOKIE_SECURE_ATTR; import java.text.MessageFormat; -import java.util.Collections; import java.util.Map; import java.util.ResourceBundle; import java.util.TreeMap; +import org.apache.catalina.LogFacade; + import jakarta.servlet.SessionCookieConfig; /** - * Class that may be used to configure various properties of cookies - * used for session tracking purposes. + * Class that may be used to configure various properties of cookies used for session tracking purposes. */ public class SessionCookieConfigImpl implements SessionCookieConfig { + private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); + private static final int DEFAULT_MAX_AGE = -1; private static final boolean DEFAULT_HTTP_ONLY = false; private static final boolean DEFAULT_SECURE = false; @@ -40,12 +49,9 @@ public class SessionCookieConfigImpl implements SessionCookieConfig { private String name = DEFAULT_NAME; - private final Map attributes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private final Map attributes = new TreeMap<>(CASE_INSENSITIVE_ORDER); private final StandardContext ctx; - private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); - - /** * Constructor */ @@ -53,215 +59,156 @@ public SessionCookieConfigImpl(StandardContext ctx) { this.ctx = ctx; } - /** * @param name the cookie name to use * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setName(String name) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"name", ctx.getName()}); - throw new IllegalStateException(msg); - } + checkContextInitialized("name"); this.name = name; ctx.setSessionCookieName(name); } - /** - * @return the cookie name set via {@link #setName}, or - * JSESSIONID if {@link #setName} was never called + * @return the cookie name set via {@link #setName}, or JSESSIONID if {@link #setName} was never called */ @Override public String getName() { return name; } - /** * @param domain the cookie domain to use * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setDomain(String domain) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"dnmain", ctx.getName()}); - throw new IllegalStateException(msg); - } - setAttribute(Constants.COOKIE_DOMAIN_ATTR, domain); + checkContextInitialized("domain"); + setAttribute(COOKIE_DOMAIN_ATTR, domain); } - /** - * @return the cookie domain set via {@link #setDomain}, or - * null if {@link #setDomain} was never called + * @return the cookie domain set via {@link #setDomain}, or null if {@link #setDomain} was never called */ @Override public String getDomain() { - return getAttribute(Constants.COOKIE_DOMAIN_ATTR); + return getAttribute(COOKIE_DOMAIN_ATTR); } - /** * @param path the cookie path to use * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setPath(String path) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"path", ctx.getName()}); - throw new IllegalStateException(msg); - } - setAttribute(Constants.COOKIE_PATH_ATTR, path); + checkContextInitialized("path"); + setAttribute(COOKIE_PATH_ATTR, path); } - /** - * @return the cookie path set via {@link #setPath}, or the context - * path of the ServletContext from which this - * SessionCookieConfig was acquired if {@link #setPath} - * was never called + * @return the cookie path set via {@link #setPath}, or the context path of the ServletContext from which this + * SessionCookieConfig was acquired if {@link #setPath} was never called */ @Override public String getPath() { - return getAttribute(Constants.COOKIE_PATH_ATTR); + return getAttribute(COOKIE_PATH_ATTR); } - /** * @param comment the cookie comment to use * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setComment(String comment) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"comment", ctx.getName()}); - throw new IllegalStateException(msg); - } + checkContextInitialized("comment"); setAttribute(Constants.COOKIE_COMMENT_ATTR, comment); } - /** - * @return the cookie comment set via {@link #setComment}, or - * null if {@link #setComment} was never called + * @return the cookie comment set via {@link #setComment}, or null if {@link #setComment} was never called */ @Override public String getComment() { return getAttribute(Constants.COOKIE_COMMENT_ATTR); } - /** - * @param httpOnly true if the session tracking cookies created - * on behalf of the ServletContext from which this - * SessionCookieConfig was acquired shall be marked as - * HttpOnly, false otherwise + * @param httpOnly true if the session tracking cookies created on behalf of the ServletContext from which this + * SessionCookieConfig was acquired shall be marked as HttpOnly, false otherwise * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setHttpOnly(boolean httpOnly) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"httpOnly", ctx.getName()}); - throw new IllegalStateException(msg); - } - setAttribute(Constants.COOKIE_HTTP_ONLY_ATTR, String.valueOf(httpOnly)); + checkContextInitialized("httpOnly"); + setAttribute(COOKIE_HTTP_ONLY_ATTR, String.valueOf(httpOnly)); } - /** - * @return true if the session tracking cookies created on behalf of the - * ServletContext from which this SessionCookieConfig - * was acquired will be marked as HttpOnly, false otherwise + * @return true if the session tracking cookies created on behalf of the ServletContext from which this + * SessionCookieConfig was acquired will be marked as HttpOnly, false otherwise */ @Override public boolean isHttpOnly() { - String value = getAttribute(Constants.COOKIE_HTTP_ONLY_ATTR); + String value = getAttribute(COOKIE_HTTP_ONLY_ATTR); return value == null ? DEFAULT_HTTP_ONLY : Boolean.parseBoolean(value); } - /** - * @param secure true if the session tracking cookies created on - * behalf of the ServletContext from which this - * SessionCookieConfig was acquired shall be marked as - * secure even if the request that initiated the corresponding - * session is using plain HTTP instead of HTTPS, and false if they - * shall be marked as secure only if the request that initiated - * the corresponding session was also secure + * @param secure true if the session tracking cookies created on behalf of the ServletContext from which this + * SessionCookieConfig was acquired shall be marked as secure even if the request that initiated the + * corresponding session is using plain HTTP instead of HTTPS, and false if they shall be marked as secure only + * if the request that initiated the corresponding session was also secure * - * @throws IllegalStateException if the ServletContext - * from which this SessionCookieConfig was acquired has - * already been initialized + * @throws IllegalStateException if the ServletContext from which this SessionCookieConfig was + * acquired has already been initialized */ @Override public void setSecure(boolean secure) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"secure", ctx.getName()}); - throw new IllegalStateException(msg); - } - setAttribute(Constants.COOKIE_SECURE_ATTR, String.valueOf(secure)); + checkContextInitialized("secure"); + setAttribute(COOKIE_SECURE_ATTR, String.valueOf(secure)); } - /** - * @return true if the session tracking cookies created on behalf of the - * ServletContext from which this SessionCookieConfig - * was acquired will be marked as secure even if the request - * that initiated the corresponding session is using plain HTTP - * instead of HTTPS, and false if they will be marked as secure - * only if the request that initiated the corresponding session was - * also secure + * @return true if the session tracking cookies created on behalf of the ServletContext from which this + * SessionCookieConfig was acquired will be marked as secure even if the request that initiated the + * corresponding session is using plain HTTP instead of HTTPS, and false if they will be marked as secure only if + * the request that initiated the corresponding session was also secure */ @Override public boolean isSecure() { - String value = getAttribute(Constants.COOKIE_SECURE_ATTR); + String value = getAttribute(COOKIE_SECURE_ATTR); return value == null ? DEFAULT_SECURE : Boolean.parseBoolean(value); } - @Override public void setMaxAge(int maxAge) { - if (ctx.isContextInitializedCalled()) { - String msg = MessageFormat.format(rb.getString(LogFacade.SESSION_COOKIE_CONFIG_ALREADY_INIT), - new Object[] {"maxAge", ctx.getName()}); - throw new IllegalStateException(msg); - } - setAttribute(Constants.COOKIE_MAX_AGE_ATTR, String.valueOf(maxAge)); + checkContextInitialized("maxAge"); + setAttribute(COOKIE_MAX_AGE_ATTR, String.valueOf(maxAge)); } - @Override public int getMaxAge() { - String value = getAttribute(Constants.COOKIE_MAX_AGE_ATTR); + String value = getAttribute(COOKIE_MAX_AGE_ATTR); return value == null ? DEFAULT_MAX_AGE : Integer.parseInt(value); } @Override public void setAttribute(String name, String value) { + checkContextInitialized("attribute"); + checkValid(name, value); + this.attributes.put(name, value); } @@ -272,6 +219,23 @@ public String getAttribute(String name) { @Override public Map getAttributes() { - return Collections.unmodifiableMap(this.attributes); + return unmodifiableMap(this.attributes); + } + + private void checkContextInitialized(String parameter) { + if (ctx.isContextInitializedCalled()) { + throw new IllegalStateException(MessageFormat.format(rb.getString(SESSION_COOKIE_CONFIG_ALREADY_INIT), + new Object[] { parameter, ctx.getName() })); + } + } + + private void checkValid(String name, String value) { + if (name == null) { + throw new IllegalArgumentException(name + " cannot be null"); + } + + if (name.equals("DEFAULT_MAX_AGE")) { + Integer.parseInt(value); + } } } From 286a1b6a6372db90ea352e60206d4e91726fd64b Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Mon, 11 Apr 2022 00:31:42 +0200 Subject: [PATCH 10/11] Refactoring Signed-off-by: Arjan Tijms --- .../grizzly/CoyoteConnectorLauncher.java | 117 ++-- .../grizzly/DummyConnectorLauncher.java | 14 +- .../connector/ClientAbortException.java | 15 +- .../apache/catalina/connector/Connector.java | 571 +++++++----------- .../catalina/connector/CoyotePrincipal.java | 27 +- .../catalina/connector/CoyoteWriter.java | 104 ++-- 6 files changed, 321 insertions(+), 527 deletions(-) diff --git a/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/CoyoteConnectorLauncher.java b/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/CoyoteConnectorLauncher.java index 4a0d797ba79..1d15f6a8bde 100644 --- a/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/CoyoteConnectorLauncher.java +++ b/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/CoyoteConnectorLauncher.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -25,68 +26,49 @@ import org.glassfish.grizzly.http.server.HttpHandler; /** - * Abstract the protocol implementation, including threading, etc. - * Processor is single threaded and specific to stream-based protocols, - * will not fit Jk protocols like JNI. + * Abstract the protocol implementation, including threading, etc. Processor is single threaded and specific to + * stream-based protocols, will not fit Jk protocols like JNI. * * @author Remy Maucherat * @author Costin Manolache */ -public class CoyoteConnectorLauncher implements ProtocolHandler -{ - // START SJSAS 6439313 - protected boolean blocking = false; - // END SJSAS 6439313 +public class CoyoteConnectorLauncher implements ProtocolHandler { + protected boolean blocking; /** - * The SelectorThread implementation class. Not used when - * Coyote is used. + * The SelectorThread implementation class. Not used when Coyote is used. */ - protected String selectorThreadImpl = null; - + protected String selectorThreadImpl; public CoyoteConnectorLauncher() { - // START SJSAS 6439313 - this(false,false,null); + this(false, false, null); } - - public CoyoteConnectorLauncher(boolean secure, boolean blocking, - String selectorThreadImpl) { + public CoyoteConnectorLauncher(boolean secure, boolean blocking, String selectorThreadImpl) { this.secure = secure; this.blocking = blocking; this.selectorThreadImpl = selectorThreadImpl; } - public int getMaxHttpHeaderSize() { return maxHttpHeaderSize; } - public void setMaxHttpHeaderSize(int valueI) { maxHttpHeaderSize = valueI; setAttribute("maxHttpHeaderSize", "" + valueI); } - - /** Pass config info + /** + * Pass config info */ @Override - public void setAttribute( String name, Object value ) { - + public void setAttribute(String name, Object value) { attributes.put(name, value); -/* - if ("maxKeepAliveRequests".equals(name)) { - maxKeepAliveRequests = Integer.parseInt((String) value.toString()); - } else if ("port".equals(name)) { - setPort(Integer.parseInt((String) value.toString())); - } -*/ } @Override - public Object getAttribute( String key ) { + public Object getAttribute(String key) { return attributes.get(key); } @@ -101,14 +83,15 @@ public void setProperty(String name, String value) { * Get a property */ public String getProperty(String name) { - return (String)getAttribute(name); + return (String) getAttribute(name); } - /** The adapter, used to call the connector + /** + * The adapter, used to call the connector */ @Override public void setHandler(HttpHandler adapter) { - this.adapter=adapter; + this.adapter = adapter; } @Override @@ -116,8 +99,8 @@ public HttpHandler getHandler() { return adapter; } - - /** Start the protocol + /** + * Start the protocol */ @Override public void init() throws Exception { @@ -138,24 +121,22 @@ public void destroy() throws Exception { // socket factory attributes ( XXX replace with normal setters ) protected Map attributes = new HashMap<>(); - protected String socketFactoryName=null; - protected String sslImplementationName=null; + protected String socketFactoryName = null; + protected String sslImplementationName = null; - private int maxKeepAliveRequests=100; // as in Apache HTTPD server - protected int timeout = 300000; // 5 minutes as in Apache HTTPD server + private int maxKeepAliveRequests = 100; // as in Apache HTTPD server + protected int timeout = 300000; // 5 minutes as in Apache HTTPD server protected int maxPostSize = 2 * 1024 * 1024; protected int maxHttpHeaderSize = 4 * 1024; private String reportedname; - protected int socketCloseDelay=-1; + protected int socketCloseDelay = -1; protected boolean disableUploadTimeout = true; protected HttpHandler adapter; - // START OF SJSAS PE 8.1 6172948 /** * The input request buffer size. */ protected int requestBufferSize = 4096; - // END OF SJSAS PE 8.1 6172948 /** * Compression value. @@ -164,12 +145,11 @@ public void destroy() throws Exception { // -------------------- Pool setup -------------------- - public String getSocketFactory() { return socketFactoryName; } - public void setSocketFactory( String valueS ) { + public void setSocketFactory(String valueS) { socketFactoryName = valueS; setAttribute("socketFactory", valueS); } @@ -178,8 +158,8 @@ public String getSSLImplementation() { return sslImplementationName; } - public void setSSLImplementation( String valueS) { - sslImplementationName=valueS; + public void setSSLImplementation(String valueS) { + sslImplementationName = valueS; setAttribute("sslImplementation", valueS); } @@ -213,7 +193,7 @@ public String getKeystore() { return getProperty("keystore"); } - public void setKeystore( String k ) { + public void setKeystore(String k) { setAttribute("keystore", k); } @@ -221,20 +201,18 @@ public String getKeypass() { return getProperty("keypass"); } - public void setKeypass( String k ) { + public void setKeypass(String k) { attributes.put("keypass", k); - //setAttribute("keypass", k); } public String getKeytype() { return getProperty("keystoreType"); } - public void setKeytype( String k ) { + public void setKeytype(String k) { setAttribute("keystoreType", k); } - // START GlassFish Issue 657 public void setTruststore(String truststore) { setAttribute("truststore", truststore); } @@ -242,13 +220,12 @@ public void setTruststore(String truststore) { public void setTruststoreType(String truststoreType) { setAttribute("truststoreType", truststoreType); } - // END GlassFish Issue 657 public String getClientauth() { return getProperty("clientauth"); } - public void setClientauth( String k ) { + public void setClientauth(String k) { setAttribute("clientauth", k); } @@ -256,7 +233,7 @@ public String getProtocol() { return getProperty("protocol"); } - public void setProtocol( String k ) { + public void setProtocol(String k) { setAttribute("protocol", k); } @@ -272,7 +249,7 @@ public String getAlgorithm() { return getProperty("algorithm"); } - public void setAlgorithm( String k ) { + public void setAlgorithm(String k) { setAttribute("algorithm", k); } @@ -280,21 +257,19 @@ public boolean getSecure() { return secure; } - public void setSecure( boolean b ) { - secure=b; + public void setSecure(boolean b) { + secure = b; setAttribute("secure", "" + b); } - // START SJSAS 6439313 public boolean getBlocking() { return blocking; } - public void setBlocking( boolean b ) { - blocking=b; + public void setBlocking(boolean b) { + blocking = b; setAttribute("blocking", "" + b); } - // END SJSAS 6439313 public String getCiphers() { return getProperty("ciphers"); @@ -316,7 +291,8 @@ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; } - /** Set the maximum number of Keep-Alive requests that we will honor. + /** + * Set the maximum number of Keep-Alive requests that we will honor. */ public void setMaxKeepAliveRequests(int mkar) { maxKeepAliveRequests = mkar; @@ -327,15 +303,13 @@ public int getSocketCloseDelay() { return socketCloseDelay; } - public void setSocketCloseDelay( int d ) { - socketCloseDelay=d; + public void setSocketCloseDelay(int d) { + socketCloseDelay = d; setAttribute("socketCloseDelay", "" + d); } - protected static ServerSocketFactory string2SocketFactory(String val) - throws ClassNotFoundException, IllegalAccessException, InstantiationException { - Class chC = Class.forName(val); - return (ServerSocketFactory) chC.newInstance(); + protected static ServerSocketFactory string2SocketFactory(String val) throws ReflectiveOperationException, IllegalArgumentException, SecurityException { + return (ServerSocketFactory) Class.forName(val).getDeclaredConstructor().newInstance(); } public int getTimeout() { @@ -355,7 +329,6 @@ public void setReportedname(String reportedName) { reportedname = reportedName; } - // START OF SJSAS PE 8.1 6172948 /** * Set the request input buffer size */ @@ -363,12 +336,10 @@ public void setBufferSize(int requestBufferSize) { this.requestBufferSize = requestBufferSize; } - /** * Return the request input buffer size */ - public int getBufferSize(){ + public int getBufferSize() { return requestBufferSize; } - // END OF SJSAS PE 8.1 6172948 } diff --git a/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/DummyConnectorLauncher.java b/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/DummyConnectorLauncher.java index c13dd4f2b66..c18daa5724b 100644 --- a/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/DummyConnectorLauncher.java +++ b/appserver/web/web-core/src/main/java/com/sun/enterprise/web/connector/grizzly/DummyConnectorLauncher.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -18,8 +19,7 @@ package com.sun.enterprise.web.connector.grizzly; /** - * Dummy Connector Launcher that doesn't start any listener like Grizzly - * or Coyote. + * Dummy Connector Launcher that doesn't start any listener like Grizzly or Coyote. * * @author Jean-Francois Arcand */ @@ -27,9 +27,8 @@ public class DummyConnectorLauncher extends CoyoteConnectorLauncher { // ------------------------------------------------------- Constructor --// - public DummyConnectorLauncher(boolean secure, boolean blocking, - String selectorThreadImpl) { - super(secure,blocking,selectorThreadImpl); + public DummyConnectorLauncher(boolean secure, boolean blocking, String selectorThreadImpl) { + super(secure, blocking, selectorThreadImpl); } /** @@ -39,17 +38,12 @@ public DummyConnectorLauncher(boolean secure, boolean blocking, public void init() throws Exception { } - @Override public void start() throws Exception { } - @Override public void destroy() throws Exception { } - - } - diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ClientAbortException.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ClientAbortException.java index 9bbedfbdd97..cd8a3a7a16d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ClientAbortException.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/ClientAbortException.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -20,18 +21,16 @@ import java.io.IOException; /** - * Wrap an IOException identifying it as being caused by an abort - * of a request by a remote client. + * Wrap an IOException identifying it as being caused by an abort of a request by a remote client. * * @author Glenn L. Nielsen * @version $Revision: 1.3 $ $Date: 2005/12/08 01:27:28 $ */ - public final class ClientAbortException extends IOException { + private static final long serialVersionUID = 1L; - //------------------------------------------------------------ Constructors - + // ------------------------------------------------------------ Constructors /** * Construct a new ClientAbortException with no other information. @@ -40,7 +39,6 @@ public ClientAbortException() { super(); } - /** * Construct a new ClientAbortException for the specified message. * @@ -50,7 +48,6 @@ public ClientAbortException(String message) { super(message); } - /** * Construct a new ClientAbortException for the specified throwable. * @@ -60,10 +57,8 @@ public ClientAbortException(Throwable throwable) { super(throwable); } - /** - * Construct a new ClientAbortException for the specified message - * and throwable. + * Construct a new ClientAbortException for the specified message and throwable. * * @param message Message describing this exception * @param throwable Throwable that caused this exception diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Connector.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Connector.java index 2c9a6ade000..83dc83e22db 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Connector.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Connector.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -17,7 +18,15 @@ package org.apache.catalina.connector; -import com.sun.appserv.ProxyHandler; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.INFO; +import static java.util.logging.Level.WARNING; +import static org.apache.catalina.Globals.CERTIFICATES_ATTR; +import static org.apache.catalina.Globals.SSL_CERTIFICATE_ATTR; +import static org.apache.catalina.LogFacade.CONNECTOR_BEEN_STARTED; +import static org.apache.catalina.LogFacade.CONNECTOR_NOT_BEEN_STARTED; +import static org.apache.catalina.LogFacade.PROTOCOL_HANDLER_DESTROY_FAILED_EXCEPTION; +import static org.apache.catalina.LogFacade.PROTOCOL_HANDLER_START_FAILED_EXCEPTION; import java.lang.reflect.Constructor; import java.net.URLEncoder; @@ -37,7 +46,6 @@ import org.apache.catalina.Container; import org.apache.catalina.Context; -import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; @@ -51,6 +59,8 @@ import org.glassfish.grizzly.http.server.util.Mapper; import org.glassfish.web.util.IntrospectionUtils; +import com.sun.appserv.ProxyHandler; + import jakarta.servlet.http.HttpServletRequest; /** @@ -60,9 +70,7 @@ * @author Remy Maucherat * @version $Revision: 1.23 $ $Date: 2007/07/09 20:46:45 $ */ -public class Connector - implements org.apache.catalina.Connector, Lifecycle -{ +public class Connector implements org.apache.catalina.Connector, Lifecycle { private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); @@ -70,14 +78,11 @@ public class Connector // START SJSAS 6363251 /** - * Coyote Adapter class name. - * Defaults to the CoyoteAdapter. + * Coyote Adapter class name. Defaults to the CoyoteAdapter. */ - private String defaultClassName = - "org.apache.catalina.connector.CoyoteAdapter"; + private String defaultClassName = "org.apache.catalina.connector.CoyoteAdapter"; // END SJSAS 6363251 - // ----------------------------------------------------- Instance Variables /** @@ -88,7 +93,7 @@ public class Connector /** * The Service we are associated with (if any). */ - private Service service = null; + private Service service; /** * The accept count for this Connector. @@ -96,10 +101,9 @@ public class Connector private int acceptCount = 10; /** - * The IP address on which to bind, if any. If null, all - * addresses on the server will be bound. + * The IP address on which to bind, if any. If null, all addresses on the server will be bound. */ - private String address = null; + private String address; /** * Do we allow TRACE ? @@ -114,7 +118,7 @@ public class Connector /** * The Container used for processing requests received by this Connector. */ - protected Container container = null; + protected Container container; /** * Compression value. @@ -129,12 +133,12 @@ public class Connector /** * The "enable DNS lookups" flag for this Connector. */ - private boolean enableLookups = false; + private boolean enableLookups; /** * The server socket factory for this component. */ - private ServerSocketFactory factory = null; + private ServerSocketFactory factory; /** * Maximum size of a HTTP header. 4KB is the default. @@ -149,8 +153,7 @@ public class Connector /** * Descriptive information about this Connector implementation. */ - private static final String info = - "org.apache.catalina.connector.Connector/2.0"; + private static final String info = "org.apache.catalina.connector.Connector/2.0"; /** * The lifecycle event support for this component. @@ -168,27 +171,22 @@ public class Connector private int maxProcessors = 20; /** - * Linger value on the incoming connection. - * Note : a value inferior to 0 means no linger. + * Linger value on the incoming connection. Note : a value inferior to 0 means no linger. */ private int connectionLinger = Constants.DEFAULT_CONNECTION_LINGER; /** - * Timeout value on the incoming connection. - * Note : a value of 0 means no timeout. + * Timeout value on the incoming connection. Note : a value of 0 means no timeout. */ private int connectionTimeout = Constants.DEFAULT_CONNECTION_TIMEOUT; /** - * Timeout value on the incoming connection during request processing. - * Note : a value of 0 means no timeout. + * Timeout value on the incoming connection during request processing. Note : a value of 0 means no timeout. */ - private int connectionUploadTimeout = - Constants.DEFAULT_CONNECTION_UPLOAD_TIMEOUT; + private int connectionUploadTimeout = Constants.DEFAULT_CONNECTION_UPLOAD_TIMEOUT; /** - * Timeout value on the server socket. - * Note : a value of 0 means no timeout. + * Timeout value on the server socket. Note : a value of 0 means no timeout. */ private int serverSocketTimeout = Constants.DEFAULT_SERVER_SOCKET_TIMEOUT; @@ -198,18 +196,16 @@ public class Connector private int port = 8080; /** - * The server name to which we should pretend requests to this Connector - * were directed. This is useful when operating Tomcat behind a proxy - * server, so that redirects get constructed accurately. If not specified, - * the server name included in the Host header is used. + * The server name to which we should pretend requests to this Connector were directed. This is useful when operating + * Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the server name + * included in the Host header is used. */ - private String proxyName = null; + private String proxyName; /** - * The server port to which we should pretend requests to this Connector - * were directed. This is useful when operating Tomcat behind a proxy - * server, so that redirects get constructed accurately. If not specified, - * the port number specified by the port property is used. + * The server port to which we should pretend requests to this Connector were directed. This is useful when operating + * Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the port number + * specified by the port property is used. */ private int proxyPort = 0; @@ -218,44 +214,34 @@ public class Connector */ private int redirectPort = 443; - // BEGIN S1AS 5000999 /** * The default host. */ private String defaultHost; - // END S1AS 5000999 /** - * The request scheme that will be set on all requests received - * through this connector. + * The request scheme that will be set on all requests received through this connector. */ private String scheme = "http"; /** - * The secure connection flag that will be set on all requests received - * through this connector. + * The secure connection flag that will be set on all requests received through this connector. */ private boolean secure = false; - // START SJSAS 6439313 /** - * The blocking connection flag that will be set on all requests received - * through this connector. + * The blocking connection flag that will be set on all requests received through this connector. */ private boolean blocking = false; - // END SJSAS 6439313 - /** For jk, do tomcat authentication if true, trust server if false + /** + * For jk, do tomcat authentication if true, trust server if false */ private boolean tomcatAuthentication = true; - - /** - * Flag to disable setting a seperate time-out for uploads. - * If true, then the timeout parameter is - * ignored. If false, then the timeout - * parameter is used to control uploads. + * Flag to disable setting a seperate time-out for uploads. If true, then the timeout + * parameter is ignored. If false, then the timeout parameter is used to control uploads. */ private boolean disableUploadTimeout = true; @@ -265,14 +251,12 @@ public class Connector private int maxKeepAliveRequests = 100; /** - * Maximum size of a POST which will be automatically parsed by the - * container. 2MB by default. + * Maximum size of a POST which will be automatically parsed by the container. 2MB by default. */ private int maxPostSize = 2 * 1024 * 1024; /** - * Maximum size of a POST which will be saved by the container - * during authentication. 4kB by default + * Maximum size of a POST which will be saved by the container during authentication. 4kB by default */ protected int maxSavePostSize = 4 * 1024; @@ -286,32 +270,20 @@ public class Connector */ private boolean started = false; - /** - * The shutdown signal to our background thread - */ - private boolean stopped = false; - - /** - * The background thread. - */ - private Thread thread = null; - /** * Use TCP no delay ? */ private boolean tcpNoDelay = true; /** - * Coyote Protocol handler class name. - * Defaults to the Coyote HTTP/1.1 protocolHandler. + * Coyote Protocol handler class name. Defaults to the Coyote HTTP/1.1 protocolHandler. */ - private String protocolHandlerClassName = - "com.sun.enterprise.web.connector.grizzly.CoyoteConnectorLauncher"; + private String protocolHandlerClassName = "com.sun.enterprise.web.connector.grizzly.CoyoteConnectorLauncher"; /** * Coyote protocol handler. */ - private ProtocolHandler protocolHandler = null; + private ProtocolHandler protocolHandler; private String instanceName; @@ -320,7 +292,7 @@ public class Connector */ private String name; - private HttpHandler handler = null; + private HttpHandler handler; /** * Mapper. @@ -330,31 +302,21 @@ public class Connector /** * URI encoding. */ - /* GlassFish Issue 2339 - private String uriEncoding = null; - */ - // START GlassFish Issue 2339 private String uriEncoding = "UTF-8"; - // END GlassFish Issue 2339 - // START SJSAS 6331392 private boolean enabled = true; - // END SJSAS 6331392 - // START S1AS 6188932 /** - * Flag indicating whether this connector is receiving its requests from - * a trusted intermediate server + * Flag indicating whether this connector is receiving its requests from a trusted intermediate server */ protected boolean authPassthroughEnabled = false; - protected ProxyHandler proxyHandler = null; - // END S1AS 6188932 + protected ProxyHandler proxyHandler; /** * The SelectorThread implementation class. */ - private String selectorThreadImpl = null; + private String selectorThreadImpl; private String jvmRoute; @@ -409,8 +371,7 @@ public String getCompression() { /** * Set the value of compression. * - * @param compression The new compression value, which can be "on", "off" - * or "force" + * @param compression The new compression value, which can be "on", "off" or "force" */ public void setCompression(String compression) { this.compression = compression; @@ -520,7 +481,7 @@ public void setAddress(String address) { } /** - * True if the TRACE method is allowed. Default value is "false". + * True if the TRACE method is allowed. Default value is "false". */ public boolean getAllowTrace() { return allowTrace; @@ -561,8 +522,7 @@ public void setBufferSize(int bufferSize) { } /** - * Return the Container used for processing requests received by this - * Connector. + * Return the Container used for processing requests received by this Connector. */ @Override public Container getContainer() { @@ -570,8 +530,7 @@ public Container getContainer() { } /** - * Set the Container used for processing requests received by this - * Connector. + * Set the Container used for processing requests received by this Connector. * * @param container The new Container to use */ @@ -650,9 +609,10 @@ public Mapper getMapper() { /** * Set the {@link Mapper}. + * * @param mapper */ - public void setMapper(Mapper mapper){ + public void setMapper(Mapper mapper) { this.mapper = mapper; } @@ -691,29 +651,27 @@ public void setMaxProcessors(int maxProcessors) { } /** - * Return the maximum size of a POST which will be automatically - * parsed by the container. + * Return the maximum size of a POST which will be automatically parsed by the container. */ public int getMaxPostSize() { return maxPostSize; } /** - * Set the maximum size of a POST which will be automatically - * parsed by the container. + * Set the maximum size of a POST which will be automatically parsed by the container. * - * @param maxPostSize The new maximum size in bytes of a POST which will - * be automatically parsed by the container + * @param maxPostSize The new maximum size in bytes of a POST which will be automatically parsed by the container */ + @Override public void setMaxPostSize(int maxPostSize) { this.maxPostSize = maxPostSize; setProperty("maxPostSize", String.valueOf(maxPostSize)); } /** - * Return the maximum size of a POST which will be saved by the container - * during authentication. + * Return the maximum size of a POST which will be saved by the container during authentication. */ + @Override public int getMaxSavePostSize() { return (maxSavePostSize); @@ -721,11 +679,10 @@ public int getMaxSavePostSize() { } /** - * Set the maximum size of a POST which will be saved by the container - * during authentication. + * Set the maximum size of a POST which will be saved by the container during authentication. * - * @param maxSavePostSize The new maximum size in bytes of a POST which will - * be saved by the container during authentication. + * @param maxSavePostSize The new maximum size in bytes of a POST which will be saved by the container during + * authentication. */ public void setMaxSavePostSize(int maxSavePostSize) { @@ -753,7 +710,7 @@ public void setPort(int port) { /** * Sets the name of this Connector. */ - public void setName(String name){ + public void setName(String name) { this.name = name; } @@ -761,7 +718,7 @@ public void setName(String name){ * Gets the name of this Connector. */ @Override - public String getName(){ + public String getName() { return name; } @@ -782,11 +739,9 @@ public String getInstanceName() { * Return the Coyote protocol handler in use. */ public String getProtocol() { - if ("org.glassfish.grizzly.tcp.http11.Http11Protocol".equals - (getProtocolHandlerClassName())) { + if ("org.glassfish.grizzly.tcp.http11.Http11Protocol".equals(getProtocolHandlerClassName())) { return "HTTP/1.1"; - } else if ("org.apache.jk.server.JkCoyoteHandler".equals - (getProtocolHandlerClassName())) { + } else if ("org.apache.jk.server.JkCoyoteHandler".equals(getProtocolHandlerClassName())) { return "AJP/1.3"; } return null; @@ -799,11 +754,9 @@ public String getProtocol() { */ public void setProtocol(String protocol) { if (protocol.equals("HTTP/1.1")) { - setProtocolHandlerClassName - ("org.glassfish.grizzly.tcp.http11.Http11Protocol"); + setProtocolHandlerClassName("org.glassfish.grizzly.tcp.http11.Http11Protocol"); } else if (protocol.equals("AJP/1.3")) { - setProtocolHandlerClassName - ("org.apache.jk.server.JkCoyoteHandler"); + setProtocolHandlerClassName("org.apache.jk.server.JkCoyoteHandler"); } else { setProtocolHandlerClassName(null); } @@ -817,8 +770,7 @@ public String getProtocolHandlerClassName() { } /** - * Set the class name of the Coyote protocol handler which will be used - * by the connector. + * Set the class name of the Coyote protocol handler which will be used by the connector. * * @param protocolHandlerClassName The new class name */ @@ -846,7 +798,7 @@ public String getProxyName() { * @param proxyName The new proxy server name */ public void setProxyName(String proxyName) { - if(proxyName != null && proxyName.length() > 0) { + if (proxyName != null && proxyName.length() > 0) { this.proxyName = proxyName; setProperty("proxyName", proxyName); } else { @@ -873,9 +825,8 @@ public void setProxyPort(int proxyPort) { } /** - * Return the port number to which a request should be redirected if - * it comes in on a non-SSL port and is subject to a security constraint - * with a transport guarantee that requires SSL. + * Return the port number to which a request should be redirected if it comes in on a non-SSL port and is subject to a + * security constraint with a transport guarantee that requires SSL. */ @Override public int getRedirectPort() { @@ -903,20 +854,19 @@ public boolean getDisableUploadTimeout() { /** * Set the flag to specify upload time-out behavior. * - * @param isDisabled If true, then the timeout - * parameter is ignored. If false, then the - * timeout parameter is used to control uploads. + * @param isDisabled If true, then the timeout parameter is ignored. If false, + * then the timeout parameter is used to control uploads. */ - public void setDisableUploadTimeout( boolean isDisabled ) { + public void setDisableUploadTimeout(boolean isDisabled) { disableUploadTimeout = isDisabled; setProperty("disableUploadTimeout", String.valueOf(isDisabled)); } /** - * Return the maximum HTTP header size. - */ + * Return the maximum HTTP header size. + */ public int getMaxHttpHeaderSize() { - return maxHttpHeaderSize; + return maxHttpHeaderSize; } /** @@ -944,8 +894,7 @@ public void setKeepAlive(boolean keepAlive) { } /** - * Return the maximum number of Keep-Alive requests to honor - * per connection. + * Return the maximum number of Keep-Alive requests to honor per connection. */ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; @@ -960,8 +909,7 @@ public void setMaxKeepAliveRequests(int mkar) { } /** - * Return the scheme that will be assigned to requests received - * through this connector. Default value is "http". + * Return the scheme that will be assigned to requests received through this connector. Default value is "http". */ @Override public String getScheme() { @@ -969,8 +917,7 @@ public String getScheme() { } /** - * Set the scheme that will be assigned to requests received through - * this connector. + * Set the scheme that will be assigned to requests received through this connector. * * @param scheme The new scheme */ @@ -981,8 +928,8 @@ public void setScheme(String scheme) { } /** - * Return the secure connection flag that will be assigned to requests - * received through this connector. Default value is "false". + * Return the secure connection flag that will be assigned to requests received through this connector. Default value is + * "false". */ @Override public boolean getSecure() { @@ -990,8 +937,7 @@ public boolean getSecure() { } /** - * Set the secure connection flag that will be assigned to requests - * received through this connector. + * Set the secure connection flag that will be assigned to requests received through this connector. * * @param secure The new secure connection flag */ @@ -1001,18 +947,16 @@ public void setSecure(boolean secure) { setProperty("secure", String.valueOf(secure)); } - // START SJSAS 6439313 /** - * Return the blocking connection flag that will be assigned to requests - * received through this connector. Default value is "false". + * Return the blocking connection flag that will be assigned to requests received through this connector. Default value + * is "false". */ public boolean getBlocking() { return blocking; } /** - * Set the blocking connection flag that will be assigned to requests - * received through this connector. + * Set the blocking connection flag that will be assigned to requests received through this connector. * * @param blocking The new blocking connection flag */ @@ -1020,7 +964,6 @@ public void setBlocking(boolean blocking) { this.blocking = blocking; setProperty("blocking", String.valueOf(blocking)); } - // END SJSAS 6439313 public boolean getTomcatAuthentication() { return tomcatAuthentication; @@ -1039,8 +982,7 @@ public boolean getTcpNoDelay() { } /** - * Set the TCP no delay flag which will be set on the socket after - * accepting a connection. + * Set the TCP no delay flag which will be set on the socket after accepting a connection. * * @param tcpNoDelay The new TCP no delay flag */ @@ -1065,42 +1007,36 @@ public String getURIEncoding() { @Override public void setURIEncoding(String uriEncoding) { if (Charset.isSupported(uriEncoding)) { - this.uriEncoding = uriEncoding; - setProperty("uRIEncoding", uriEncoding); + this.uriEncoding = uriEncoding; + setProperty("uRIEncoding", uriEncoding); } else { - if (log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, uriEncoding - + "is not supported .Setting default URLEncoding as " - + this.uriEncoding); + if (log.isLoggable(WARNING)) { + log.log(WARNING, uriEncoding + "is not supported .Setting default URLEncoding as " + this.uriEncoding); } } } /** - * Indicates whether the generation of an X-Powered-By response header for - * servlet-generated responses is enabled or disabled for this Connector. + * Indicates whether the generation of an X-Powered-By response header for servlet-generated responses is enabled or + * disabled for this Connector. * - * @return true if generation of X-Powered-By response header is enabled, - * false otherwise + * @return true if generation of X-Powered-By response header is enabled, false otherwise */ public boolean isXpoweredBy() { return xpoweredBy; } /** - * Enables or disables the generation of an X-Powered-By header (with value - * Servlet/2.4) for all servlet-generated responses returned by this - * Connector. + * Enables or disables the generation of an X-Powered-By header (with value Servlet/2.4) for all servlet-generated + * responses returned by this Connector. * - * @param xpoweredBy true if generation of X-Powered-By response header is - * to be enabled, false otherwise + * @param xpoweredBy true if generation of X-Powered-By response header is to be enabled, false otherwise */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; setProperty("xpoweredBy", String.valueOf(xpoweredBy)); } - // BEGIN S1AS 5000999 /** * Sets the default host for this Connector. * @@ -1120,14 +1056,11 @@ public void setDefaultHost(String defaultHost) { public String getDefaultHost() { return defaultHost; } - // END S1AS 5000999 - // START S1AS 6188932 /** * Returns the value of this connector's authPassthroughEnabled flag. * - * @return true if this connector is receiving its requests from - * a trusted intermediate server, false otherwise + * @return true if this connector is receiving its requests from a trusted intermediate server, false otherwise */ @Override public boolean getAuthPassthroughEnabled() { @@ -1137,8 +1070,8 @@ public boolean getAuthPassthroughEnabled() { /** * Sets the value of this connector's authPassthroughEnabled flag. * - * @param authPassthroughEnabled true if this connector is receiving its - * requests from a trusted intermediate server, false otherwise + * @param authPassthroughEnabled true if this connector is receiving its requests from a trusted intermediate server, + * false otherwise */ @Override public void setAuthPassthroughEnabled(boolean authPassthroughEnabled) { @@ -1148,8 +1081,7 @@ public void setAuthPassthroughEnabled(boolean authPassthroughEnabled) { /** * Gets the ProxyHandler instance associated with this CoyoteConnector. * - * @return ProxyHandler instance associated with this CoyoteConnector, - * or null + * @return ProxyHandler instance associated with this CoyoteConnector, or null */ @Override public ProxyHandler getProxyHandler() { @@ -1166,9 +1098,6 @@ public void setProxyHandler(ProxyHandler proxyHandler) { this.proxyHandler = proxyHandler; } - // END S1AS 6188932 - - // START SJSAS 6331392 public void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -1176,12 +1105,13 @@ public void setEnabled(boolean enabled) { public boolean isEnabled() { return enabled; } - // END SJSAS 6331392 + @Override public void setJvmRoute(String jvmRoute) { this.jvmRoute = jvmRoute; } + @Override public String getJvmRoute() { return jvmRoute; } @@ -1189,8 +1119,8 @@ public String getJvmRoute() { // --------------------------------------------------------- Public Methods /** - * Create (or allocate) and return a Request object suitable for - * specifying the contents of a Request to the responsible Container. + * Create (or allocate) and return a Request object suitable for specifying the contents of a Request to the responsible + * Container. */ @Override public org.apache.catalina.Request createRequest() { @@ -1200,8 +1130,8 @@ public org.apache.catalina.Request createRequest() { } /** - * Create (or allocate) and return a Response object suitable for - * receiving the contents of a Response from the responsible Container. + * Create (or allocate) and return a Response object suitable for receiving the contents of a Response from the + * responsible Container. */ @Override public org.apache.catalina.Response createResponse() { @@ -1210,37 +1140,31 @@ public org.apache.catalina.Response createResponse() { return response; } - // -------------------------------------------------- Monitoring Methods /** - * Fires probe event related to the fact that the given request has - * been entered the web container. + * Fires probe event related to the fact that the given request has been entered the web container. * * @param request the request object * @param host the virtual server to which the request was mapped * @param context the Context to which the request was mapped */ - public void requestStartEvent(HttpServletRequest request, Host host, - Context context) { + public void requestStartEvent(HttpServletRequest request, Host host, Context context) { // Deliberate noop }; /** - * Fires probe event related to the fact that the given request is about - * to exit from the web container. + * Fires probe event related to the fact that the given request is about to exit from the web container. * * @param request the request object * @param host the virtual server to which the request was mapped * @param context the Context to which the request was mapped * @param statusCode the response status code */ - public void requestEndEvent(HttpServletRequest request, Host host, - Context context, int statusCode) { + public void requestEndEvent(HttpServletRequest request, Host host, Context context, int statusCode) { // Deliberate noop }; - // ------------------------------------------------------ Lifecycle Methods /** @@ -1254,8 +1178,7 @@ public void addLifecycleListener(LifecycleListener listener) { } /** - * Gets the (possibly empty) list of lifecycle listeners - * associated with this Connector. + * Gets the (possibly empty) list of lifecycle listeners associated with this Connector. */ @Override public List findLifecycleListeners() { @@ -1272,16 +1195,13 @@ public void removeLifecycleListener(LifecycleListener listener) { lifecycle.removeLifecycleListener(listener); } - protected ObjectName createObjectName(String domain, String type) - throws MalformedObjectNameException { + protected ObjectName createObjectName(String domain, String type) throws MalformedObjectNameException { String encodedAddr = null; if (getAddress() != null) { encodedAddr = URLEncoder.encode(getProperty("address")); } - String addSuffix = (getAddress() == null) ? "" : ",address=" - + encodedAddr; - ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port=" - + getPort() + addSuffix); + String addSuffix = (getAddress() == null) ? "" : ",address=" + encodedAddr; + ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port=" + getPort() + addSuffix); return _oname; } @@ -1289,12 +1209,10 @@ protected ObjectName createObjectName(String domain, String type) * Initialize this connector (create ServerSocket here!) */ @Override - public void initialize() - throws LifecycleException - { + public void initialize() throws LifecycleException { if (initialized) { - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, LogFacade.CONNECTOR_BEEN_INIT); + if (log.isLoggable(INFO)) { + log.log(INFO, LogFacade.CONNECTOR_BEEN_INIT); } return; } @@ -1302,151 +1220,110 @@ public void initialize() this.initialized = true; // If the Mapper is null, do not fail and creates one by default. - if (mapper == null){ + if (mapper == null) { mapper = new Mapper(); } - if( oname == null && (container instanceof StandardEngine)) { + if (oname == null && (container instanceof StandardEngine)) { try { // we are loaded directly, via API - and no name was given to us - StandardEngine cb=(StandardEngine)container; + StandardEngine cb = (StandardEngine) container; oname = createObjectName(domain, "Connector"); - controller=oname; + controller = oname; } catch (Exception e) { log.log(Level.SEVERE, LogFacade.ERROR_REGISTER_CONNECTOR_EXCEPTION, e); } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Creating name for connector " + oname); + if (log.isLoggable(FINE)) { + log.log(FINE, "Creating name for connector " + oname); } } - - //START SJSAS 6363251 - // Initializa handler - //handler = new CoyoteAdapter(this); - //END SJSAS 6363251 - // Instantiate Adapter - //START SJSAS 6363251 - if ( handler == null){ + if (handler == null) { try { Class clazz = Class.forName(defaultClassName); - Constructor constructor = - clazz.getConstructor(new Class[]{Connector.class}); - handler = - (HttpHandler)constructor.newInstance(new Object[]{this}); + Constructor constructor = clazz.getConstructor(new Class[] { Connector.class }); + handler = (HttpHandler) constructor.newInstance(new Object[] { this }); } catch (Exception e) { - throw new LifecycleException - (rb.getString(LogFacade.FAILED_INSTANCIATE_HTTP_HANDLER_EXCEPTION), e); + throw new LifecycleException(rb.getString(LogFacade.FAILED_INSTANCIATE_HTTP_HANDLER_EXCEPTION), e); } } - //END SJSAS 6363251 // Instantiate protocol handler - if ( protocolHandler == null ) { + if (protocolHandler == null) { try { Class clazz = Class.forName(protocolHandlerClassName); // use no-arg constructor for JkCoyoteHandler if (protocolHandlerClassName.equals("org.apache.jk.server.JkCoyoteHandler")) { protocolHandler = (ProtocolHandler) clazz.newInstance(); - if (handler instanceof CoyoteAdapter){ + if (handler instanceof CoyoteAdapter) { ((CoyoteAdapter) handler).setCompatWithTomcat(true); } else { - String msg = MessageFormat.format(rb.getString(LogFacade.INVALID_ADAPTER_IMPLEMENTATION_EXCEPTION), - handler); - throw new IllegalStateException - (msg); + String msg = MessageFormat.format(rb.getString(LogFacade.INVALID_ADAPTER_IMPLEMENTATION_EXCEPTION), handler); + throw new IllegalStateException(msg); } - // START SJSAS 6439313 } else { - Constructor constructor = - clazz.getConstructor(new Class[]{Boolean.TYPE, - Boolean.TYPE, - String.class}); - - protocolHandler = (ProtocolHandler) - constructor.newInstance(secure, blocking, - selectorThreadImpl); - // END SJSAS 6439313 + Constructor constructor = clazz.getConstructor(new Class[] { Boolean.TYPE, Boolean.TYPE, String.class }); + + protocolHandler = (ProtocolHandler) constructor.newInstance(secure, blocking, selectorThreadImpl); } } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_INIT_FAILED_EXCEPTION), e); - throw new LifecycleException - (msg); + throw new LifecycleException(msg); } } protocolHandler.setHandler(handler); - IntrospectionUtils.setProperty(protocolHandler, "jkHome", - System.getProperty("catalina.base")); + IntrospectionUtils.setProperty(protocolHandler, "jkHome", System.getProperty("catalina.base")); // Configure secure socket factory // XXX For backwards compatibility only. if (factory instanceof CoyoteServerSocketFactory) { - IntrospectionUtils.setProperty(protocolHandler, "secure", - "" + true); - CoyoteServerSocketFactory ssf = - (CoyoteServerSocketFactory) factory; - IntrospectionUtils.setProperty(protocolHandler, "algorithm", - ssf.getAlgorithm()); + IntrospectionUtils.setProperty(protocolHandler, "secure", "" + true); + CoyoteServerSocketFactory ssf = (CoyoteServerSocketFactory) factory; + IntrospectionUtils.setProperty(protocolHandler, "algorithm", ssf.getAlgorithm()); if (ssf.getClientAuth()) { - IntrospectionUtils.setProperty(protocolHandler, "clientauth", - "" + ssf.getClientAuth()); + IntrospectionUtils.setProperty(protocolHandler, "clientauth", "" + ssf.getClientAuth()); } - IntrospectionUtils.setProperty(protocolHandler, "keystore", - ssf.getKeystoreFile()); - IntrospectionUtils.setProperty(protocolHandler, "randomfile", - ssf.getRandomFile()); - IntrospectionUtils.setProperty(protocolHandler, "rootfile", - ssf.getRootFile()); - - IntrospectionUtils.setProperty(protocolHandler, "keypass", - ssf.getKeystorePass()); - IntrospectionUtils.setProperty(protocolHandler, "keytype", - ssf.getKeystoreType()); - IntrospectionUtils.setProperty(protocolHandler, "protocol", - ssf.getProtocol()); - IntrospectionUtils.setProperty(protocolHandler, "protocols", - ssf.getProtocols()); - IntrospectionUtils.setProperty(protocolHandler, - "sSLImplementation", - ssf.getSSLImplementation()); - IntrospectionUtils.setProperty(protocolHandler, "ciphers", - ssf.getCiphers()); - IntrospectionUtils.setProperty(protocolHandler, "keyAlias", - ssf.getKeyAlias()); + IntrospectionUtils.setProperty(protocolHandler, "keystore", ssf.getKeystoreFile()); + IntrospectionUtils.setProperty(protocolHandler, "randomfile", ssf.getRandomFile()); + IntrospectionUtils.setProperty(protocolHandler, "rootfile", ssf.getRootFile()); + + IntrospectionUtils.setProperty(protocolHandler, "keypass", ssf.getKeystorePass()); + IntrospectionUtils.setProperty(protocolHandler, "keytype", ssf.getKeystoreType()); + IntrospectionUtils.setProperty(protocolHandler, "protocol", ssf.getProtocol()); + IntrospectionUtils.setProperty(protocolHandler, "protocols", ssf.getProtocols()); + IntrospectionUtils.setProperty(protocolHandler, "sSLImplementation", ssf.getSSLImplementation()); + IntrospectionUtils.setProperty(protocolHandler, "ciphers", ssf.getCiphers()); + IntrospectionUtils.setProperty(protocolHandler, "keyAlias", ssf.getKeyAlias()); } else { - IntrospectionUtils.setProperty(protocolHandler, "secure", - "" + secure); + IntrospectionUtils.setProperty(protocolHandler, "secure", "" + secure); } - /* Set the configured properties. This only sets the ones that were - * explicitly configured. Default values are the responsibility of - * the protocolHandler. + /* + * Set the configured properties. This only sets the ones that were explicitly configured. Default values are the + * responsibility of the protocolHandler. */ Iterator keys = properties.keySet().iterator(); - while( keys.hasNext() ) { + while (keys.hasNext()) { String name = keys.next(); String value = properties.get(name); - String trnName = translateAttributeName(name); + String trnName = translateAttributeName(name); IntrospectionUtils.setProperty(protocolHandler, trnName, value); } - try { protocolHandler.init(); } catch (Exception e) { String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_INIT_FAILED_EXCEPTION), e); - throw new LifecycleException - (msg); + throw new LifecycleException(msg); } } /* - * Translate the attribute name from the legacy Factory names to their - * internal protocol names. + * Translate the attribute name from the legacy Factory names to their internal protocol names. */ private String translateAttributeName(String name) { if ("clientAuth".equals(name)) { @@ -1476,13 +1353,13 @@ private String translateAttributeName(String name) { */ @Override public void start() throws LifecycleException { - if( !initialized ) + if (!initialized) initialize(); // Validate and update our current state if (started) { - if (log.isLoggable(Level.INFO)) { - log.log(Level.INFO, LogFacade.CONNECTOR_BEEN_STARTED); + if (log.isLoggable(INFO)) { + log.log(INFO, CONNECTOR_BEEN_STARTED); } return; } @@ -1492,9 +1369,8 @@ public void start() throws LifecycleException { try { protocolHandler.start(); } catch (Exception e) { - String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_START_FAILED_EXCEPTION), e); - throw new LifecycleException - (msg); + String msg = MessageFormat.format(rb.getString(PROTOCOL_HANDLER_START_FAILED_EXCEPTION), e); + throw new LifecycleException(msg); } } @@ -1509,7 +1385,7 @@ public void stop() throws LifecycleException { // Validate and update our current state if (!started) { - log.log(Level.SEVERE, LogFacade.CONNECTOR_NOT_BEEN_STARTED); + log.log(Level.SEVERE, CONNECTOR_NOT_BEEN_STARTED); return; } @@ -1519,14 +1395,11 @@ public void stop() throws LifecycleException { try { protocolHandler.destroy(); } catch (Exception e) { - String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_DESTROY_FAILED_EXCEPTION), e); - throw new LifecycleException - (msg); + throw new LifecycleException(MessageFormat.format(rb.getString(PROTOCOL_HANDLER_DESTROY_FAILED_EXCEPTION), e)); } } - // -------------------- Management methods -------------------- public boolean getClientAuth() { @@ -1538,7 +1411,7 @@ public boolean getClientAuth() { } else { ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getClientAuth(); + ret = ((CoyoteServerSocketFactory) factory).getClientAuth(); } } @@ -1549,7 +1422,7 @@ public void setClientAuth(boolean clientAuth) { setProperty("clientauth", String.valueOf(clientAuth)); ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setClientAuth(clientAuth); + ((CoyoteServerSocketFactory) factory).setClientAuth(clientAuth); } } @@ -1558,7 +1431,7 @@ public String getKeystoreFile() { if (ret == null) { ServerSocketFactory factory = this.getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getKeystoreFile(); + ret = ((CoyoteServerSocketFactory) factory).getKeystoreFile(); } } @@ -1568,7 +1441,7 @@ public String getKeystoreFile() { public void setKeystoreFile(String keystoreFile) { setProperty("keystore", keystoreFile); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setKeystoreFile(keystoreFile); + ((CoyoteServerSocketFactory) factory).setKeystoreFile(keystoreFile); } } @@ -1578,8 +1451,8 @@ public void setKeystoreFile(String keystoreFile) { public String getKeystorePass() { String ret = getProperty("keypass"); if (ret == null) { - if (factory instanceof CoyoteServerSocketFactory ) { - return ((CoyoteServerSocketFactory)factory).getKeystorePass(); + if (factory instanceof CoyoteServerSocketFactory) { + return ((CoyoteServerSocketFactory) factory).getKeystorePass(); } } @@ -1592,24 +1465,23 @@ public String getKeystorePass() { public void setKeystorePass(String keystorePass) { setProperty("keypass", keystorePass); ServerSocketFactory factory = getFactory(); - if( factory instanceof CoyoteServerSocketFactory ) { - ((CoyoteServerSocketFactory)factory).setKeystorePass(keystorePass); + if (factory instanceof CoyoteServerSocketFactory) { + ((CoyoteServerSocketFactory) factory).setKeystorePass(keystorePass); } } /** * Gets the list of SSL cipher suites that are to be enabled * - * @return Comma-separated list of SSL cipher suites, or null if all - * cipher suites supported by the underlying SSL implementation are being - * enabled + * @return Comma-separated list of SSL cipher suites, or null if all cipher suites supported by the underlying SSL + * implementation are being enabled */ public String getCiphers() { String ret = getProperty("ciphers"); if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getCiphers(); + ret = ((CoyoteServerSocketFactory) factory).getCiphers(); } } @@ -1619,8 +1491,7 @@ public String getCiphers() { /** * Sets the SSL cipher suites that are to be enabled. * - * Only those SSL cipher suites that are actually supported by - * the underlying SSL implementation will be enabled. + * Only those SSL cipher suites that are actually supported by the underlying SSL implementation will be enabled. * * @param ciphers Comma-separated list of SSL cipher suites */ @@ -1628,13 +1499,12 @@ public void setCiphers(String ciphers) { setProperty("ciphers", ciphers); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setCiphers(ciphers); + ((CoyoteServerSocketFactory) factory).setCiphers(ciphers); } } /** - * Sets the number of seconds after which SSL sessions expire and are - * removed from the SSL sessions cache. + * Sets the number of seconds after which SSL sessions expire and are removed from the SSL sessions cache. */ public void setSslSessionTimeout(String timeout) { setProperty("sslSessionTimeout", timeout); @@ -1645,8 +1515,7 @@ public String getSslSessionTimeout() { } /** - * Sets the number of seconds after which SSL3 sessions expire and are - * removed from the SSL sessions cache. + * Sets the number of seconds after which SSL3 sessions expire and are removed from the SSL sessions cache. */ public void setSsl3SessionTimeout(String timeout) { setProperty("ssl3SessionTimeout", timeout); @@ -1668,8 +1537,8 @@ public String getSslSessionCacheSize() { } /** - * Gets the alias name of the keypair and supporting certificate chain - * used by this Connector to authenticate itself to SSL clients. + * Gets the alias name of the keypair and supporting certificate chain used by this Connector to authenticate itself to + * SSL clients. * * @return The alias name of the keypair and supporting certificate chain */ @@ -1678,7 +1547,7 @@ public String getKeyAlias() { if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getKeyAlias(); + ret = ((CoyoteServerSocketFactory) factory).getKeyAlias(); } } @@ -1686,17 +1555,16 @@ public String getKeyAlias() { } /** - * Sets the alias name of the keypair and supporting certificate chain - * used by this Connector to authenticate itself to SSL clients. + * Sets the alias name of the keypair and supporting certificate chain used by this Connector to authenticate itself to + * SSL clients. * - * @param alias The alias name of the keypair and supporting certificate - * chain + * @param alias The alias name of the keypair and supporting certificate chain */ public void setKeyAlias(String alias) { setProperty("keyAlias", alias); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setKeyAlias(alias); + ((CoyoteServerSocketFactory) factory).setKeyAlias(alias); } } @@ -1710,7 +1578,7 @@ public String getSslProtocol() { if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getProtocol(); + ret = ((CoyoteServerSocketFactory) factory).getProtocol(); } } @@ -1726,7 +1594,7 @@ public void setSslProtocol(String sslProtocol) { setProperty("sslProtocol", sslProtocol); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setProtocol(sslProtocol); + ((CoyoteServerSocketFactory) factory).setProtocol(sslProtocol); } } @@ -1740,7 +1608,7 @@ public String getSslProtocols() { if (ret == null) { ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ret = ((CoyoteServerSocketFactory)factory).getProtocols(); + ret = ((CoyoteServerSocketFactory) factory).getProtocols(); } } @@ -1756,36 +1624,31 @@ public void setSslProtocols(String sslProtocols) { setProperty("sslProtocols", sslProtocols); ServerSocketFactory factory = getFactory(); if (factory instanceof CoyoteServerSocketFactory) { - ((CoyoteServerSocketFactory)factory).setProtocols(sslProtocols); + ((CoyoteServerSocketFactory) factory).setProtocols(sslProtocols); } } - // START OF SJSAS 8.1 PE 6191830 /** * Get the underlying WebContainer certificate for the request */ @Override public X509Certificate[] getCertificates(org.apache.catalina.Request request) { - - Request cRequest = null; + Request connectorRequest = null; if (request instanceof Request) { - cRequest=(Request) request; + connectorRequest = (Request) request; } else { return null; } - X509Certificate certs[] = (X509Certificate[]) - cRequest.getAttribute(Globals.CERTIFICATES_ATTR); + X509Certificate certs[] = (X509Certificate[]) connectorRequest.getAttribute(CERTIFICATES_ATTR); if ((certs == null) || (certs.length < 1)) { - certs = (X509Certificate[]) - cRequest.getAttribute(Globals.SSL_CERTIFICATE_ATTR); + certs = (X509Certificate[]) connectorRequest.getAttribute(SSL_CERTIFICATE_ATTR); } + return certs; } - // END OF SJSAS 8.1 PE 6191830 - - // -------------------- JMX registration -------------------- + // -------------------- JMX registration -------------------- protected String domain; protected ObjectName oname; @@ -1810,37 +1673,35 @@ public String getDomain() { /** * Set the domain of this object. */ - public void setDomain(String domain){ + public void setDomain(String domain) { this.domain = domain; } public void init() throws Exception { - - if( this.getService() != null ) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Already configured"); + if (this.getService() != null) { + if (log.isLoggable(FINE)) { + log.log(FINE, "Already configured"); } return; } } public void destroy() throws Exception { - if( oname!=null && controller==oname ) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Unregister itself " + oname ); + if (oname != null && controller == oname) { + if (log.isLoggable(FINE)) { + log.log(FINE, "Unregister itself " + oname); } } - if( getService() == null) + if (getService() == null) return; getService().removeConnector(this); } - // START SJSAS 6363251 /** * Set the Adapter used by this connector. */ @Override - public void setHandler(HttpHandler handler){ + public void setHandler(HttpHandler handler) { this.handler = handler; } @@ -1848,21 +1709,19 @@ public void setHandler(HttpHandler handler){ * Get the Adapter used by this connector. */ @Override - public HttpHandler getHandler(){ + public HttpHandler getHandler() { return handler; } /** * Set the ProtocolHandler used by this connector. */ - public void setProtocolHandler(ProtocolHandler protocolHandler){ + public void setProtocolHandler(ProtocolHandler protocolHandler) { this.protocolHandler = protocolHandler; } - // END SJSAS 6363251 /** - * Get the underlying SelectorThread implementation, null if - * the default is used. + * Get the underlying SelectorThread implementation, null if the default is used. */ public String getSelectorThreadImpl() { return selectorThreadImpl; diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyotePrincipal.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyotePrincipal.java index be322679d4e..0962575eac6 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyotePrincipal.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyotePrincipal.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -21,8 +22,8 @@ import java.security.Principal; /** - * Generic implementation of java.security.Principal that - * is used to represent principals authenticated at the protocol handler level. + * Generic implementation of java.security.Principal that is used to represent principals authenticated + * at the protocol handler level. * * @author Remy Maucherat * @version $Revision: 1.2 $ $Date: 2005/12/08 01:28:34 $ @@ -32,45 +33,35 @@ public class CoyotePrincipal implements Principal, Serializable { private static final long serialVersionUID = 1L; - // ----------------------------------------------------------- Constructors - public CoyotePrincipal(String name) { - this.name = name; - } - // ------------------------------------------------------------- Properties - /** * The username of the user represented by this Principal. */ - protected String name = null; + protected String name; + @Override public String getName() { - return (this.name); + return name; } - // --------------------------------------------------------- Public Methods - /** - * Return a String representation of this object, which exposes only - * information that should be public. + * Return a String representation of this object, which exposes only information that should be public. */ + @Override public String toString() { - StringBuilder sb = new StringBuilder("CoyotePrincipal["); - sb.append(this.name); + sb.append(name); sb.append("]"); return (sb.toString()); - } - } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteWriter.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteWriter.java index 8f910f4ef7c..43f06ee38bf 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteWriter.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/CoyoteWriter.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 The Apache Software Foundation * @@ -17,12 +18,13 @@ package org.apache.catalina.connector; -import org.apache.catalina.LogFacade; +import static org.apache.catalina.LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION; import java.io.IOException; import java.io.PrintWriter; import java.util.ResourceBundle; +import org.apache.catalina.LogFacade; /** * Coyote implementation of the servlet writer. @@ -30,53 +32,40 @@ * @author Remy Maucherat * @author Kin-man Chung */ -public class CoyoteWriter - extends PrintWriter { +public class CoyoteWriter extends PrintWriter { private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); - // -------------------------------------------------------------- Constants - // No need for a do privileged block - every web app has permission to read // this by default - private static final char[] LINE_SEP = - System.getProperty("line.separator").toCharArray(); - - + private static final char[] LINE_SEP = System.getProperty("line.separator").toCharArray(); // ----------------------------------------------------- Instance Variables - protected OutputBuffer ob; protected boolean error = false; - // ----------------------------------------------------------- Constructors - public CoyoteWriter(OutputBuffer ob) { super(ob); this.ob = ob; } - // --------------------------------------------------------- Public Methods - /** - * Prevent cloning the facade. - */ - protected Object clone() - throws CloneNotSupportedException { + * Prevent cloning the facade. + */ + @Override + protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } - // -------------------------------------------------------- Package Methods - /** * Clear facade. */ @@ -91,15 +80,14 @@ void recycle() { error = false; } - // --------------------------------------------------------- Writer Methods - + @Override public void flush() { // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } if (error) @@ -113,41 +101,40 @@ public void flush() { } - + @Override public void close() { - // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } // We don't close the PrintWriter - super() is not called, // so the stream can be reused. We close ob. try { ob.close(); - } catch (IOException ex ) { + } catch (IOException ex) { // Ignore } error = false; } - + @Override public boolean checkError() { // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } flush(); return error; } - + @Override public void write(int c) { // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } if (error) @@ -161,12 +148,12 @@ public void write(int c) { } - + @Override public void write(char buf[], int off, int len) { // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } if (error) @@ -179,17 +166,16 @@ public void write(char buf[], int off, int len) { } } - + @Override public void write(char buf[]) { write(buf, 0, buf.length); } - + @Override public void write(String s, int off, int len) { - // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } if (error) @@ -203,17 +189,16 @@ public void write(String s, int off, int len) { } - + @Override public void write(String s) { write(s, 0, s.length()); } - public void write(byte[] buff, int off, int len) { // Disallow operation if the object has gone out of scope if (ob == null) { - throw new IllegalStateException(rb.getString(LogFacade.OBJECT_INVALID_SCOPE_EXCEPTION)); + throw new IllegalStateException(rb.getString(OBJECT_INVALID_SCOPE_EXCEPTION)); } if (error) @@ -226,10 +211,9 @@ public void write(byte[] buff, int off, int len) { } } - // ---------------------------------------------------- PrintWriter Methods - + @Override public void print(boolean b) { if (b) { write("true"); @@ -238,37 +222,37 @@ public void print(boolean b) { } } - + @Override public void print(char c) { write(c); } - + @Override public void print(int i) { write(String.valueOf(i)); } - + @Override public void print(long l) { write(String.valueOf(l)); } - + @Override public void print(float f) { write(String.valueOf(f)); } - + @Override public void print(double d) { write(String.valueOf(d)); } - + @Override public void print(char s[]) { write(s); } - + @Override public void print(String s) { if (s == null) { s = "null"; @@ -276,65 +260,65 @@ public void print(String s) { write(s); } - + @Override public void print(Object obj) { write(String.valueOf(obj)); } - + @Override public void println() { write(LINE_SEP); } - + @Override public void println(boolean b) { print(b); println(); } - + @Override public void println(char c) { print(c); println(); } - + @Override public void println(int i) { print(i); println(); } - + @Override public void println(long l) { print(l); println(); } - + @Override public void println(float f) { print(f); println(); } - + @Override public void println(double d) { print(d); println(); } - + @Override public void println(char c[]) { print(c); println(); } - + @Override public void println(String s) { print(s); println(); } - + @Override public void println(Object o) { print(o); println(); From 5f30a8890178d30354e18cee458a290832756e8b Mon Sep 17 00:00:00 2001 From: Arjan Tijms Date: Mon, 11 Apr 2022 00:33:19 +0200 Subject: [PATCH 11/11] Refactoring and calling new cookie generator Signed-off-by: Arjan Tijms --- .../apache/catalina/connector/Request.java | 1 - .../apache/catalina/connector/Response.java | 1316 +++++++---------- 2 files changed, 523 insertions(+), 794 deletions(-) diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java index 4ede4601ad4..0bf9345723d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Request.java @@ -2971,7 +2971,6 @@ protected void parseCookies() { try { Cookie cookie = makeCookie(scookie); cookie.setPath(scookie.getPath()); - cookie.setVersion(scookie.getVersion()); String domain = scookie.getDomain(); if (domain != null) { cookie.setDomain(scookie.getDomain()); diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java index 02203d84ab4..593221adf78 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/Response.java @@ -17,6 +17,21 @@ package org.apache.catalina.connector; +import static org.apache.catalina.Globals.JREPLICA_PARAMETER; +import static org.apache.catalina.Globals.JREPLICA_SESSION_NOTE; +import static org.apache.catalina.Globals.SESSION_PARAMETER_NAME; +import static org.apache.catalina.Globals.SESSION_VERSION_PARAMETER; +import static org.apache.catalina.LogFacade.CANNOT_CALL_SEND_ERROR_EXCEPTION; +import static org.apache.catalina.LogFacade.CANNOT_CALL_SEND_REDIRECT_EXCEPTION; +import static org.apache.catalina.LogFacade.CANNOT_CHANGE_BUFFER_SIZE_EXCEPTION; +import static org.apache.catalina.LogFacade.CANNOT_RESET_BUFFER_EXCEPTION; +import static org.apache.catalina.LogFacade.ERROR_DURING_FINISH_RESPONSE; +import static org.apache.catalina.LogFacade.GET_WRITER_BEEN_CALLED_EXCEPTION; +import static org.apache.catalina.Logger.WARNING; +import static org.apache.catalina.connector.Constants.PROXY_JROUTE; +import static org.glassfish.common.util.InputValidationUtil.getSafeHeaderName; +import static org.glassfish.common.util.InputValidationUtil.getSafeHeaderValue; +import static org.glassfish.web.util.HtmlEntityEncoder.encodeXSS; import java.io.IOException; import java.io.OutputStream; @@ -28,34 +43,36 @@ import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.TimeZone; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletResponse; -import com.sun.appserv.ProxyHandler; import org.apache.catalina.Connector; import org.apache.catalina.Context; -import org.apache.catalina.LogFacade; -import org.apache.catalina.Globals; import org.apache.catalina.HttpResponse; +import org.apache.catalina.LogFacade; import org.apache.catalina.Session; import org.apache.catalina.core.StandardContext; import org.apache.catalina.security.SecurityUtil; -import org.apache.catalina.util.CharsetMapper; import org.apache.catalina.util.RequestUtil; -import org.glassfish.common.util.InputValidationUtil; import org.glassfish.grizzly.http.util.CharChunk; -import org.glassfish.grizzly.http.util.CookieSerializerUtils; -import org.glassfish.grizzly.http.util.CookieUtils; +import org.glassfish.grizzly.http.util.CookieHeaderGenerator; import org.glassfish.grizzly.http.util.FastHttpDateFormat; import org.glassfish.grizzly.http.util.MimeHeaders; import org.glassfish.grizzly.http.util.UEncoder; -import org.glassfish.web.util.HtmlEntityEncoder; -// START S1AS 6170450 + +import com.sun.appserv.ProxyHandler; + +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; // END S1AS 6170450 @@ -67,68 +84,76 @@ * @version $Revision: 1.22 $ $Date: 2007/05/05 05:32:43 $ */ -public class Response - implements HttpResponse, HttpServletResponse { +public class Response implements HttpResponse, HttpServletResponse { // ------------------------------------------------------ Static variables + public static final String HTTP_RESPONSE_DATE_HEADER = "EEE, dd MMM yyyy HH:mm:ss zzz"; + + /** + * Descriptive information about this Response implementation. + */ + protected static final String info = "org.apache.catalina.connector.Response/1.0"; + private static final Logger log = LogFacade.getLogger(); private static final ResourceBundle rb = log.getResourceBundle(); - /** * Whether or not to enforce scope checking of this object. */ - private static boolean enforceScope = false; + private static boolean enforceScope; + + // ----------------------------------------------------- Instance Variables + + private String detailErrorMsg; - public static final String HTTP_RESPONSE_DATE_HEADER = - "EEE, dd MMM yyyy HH:mm:ss zzz"; + /** + * The date format we will use for creating date headers. + */ + protected SimpleDateFormat format; /** - * Descriptive information about this Response implementation. + * Associated context. + */ + protected Context context; + + protected boolean upgrade; + + /** + * Associated Catalina connector. + */ + protected Connector connector; + + /** + * The request with which this response is associated. */ - protected static final String info = - "org.apache.catalina.connector.Response/1.0"; + protected Request connectorRequest; + /** + * The facade associated with this response. + */ + protected ResponseFacade connectorResponsefacade; + + /** + * Grizzly response. + */ + protected org.glassfish.grizzly.http.server.Response grizzlyResponse; // ----------------------------------------------------------- Constructors public Response() { - // START OF SJSAS 6231069 outputBuffer = new OutputBuffer(); outputStream = new CoyoteOutputStream(outputBuffer); writer = createWriter(outputBuffer); - // END OF SJSAS 6231069 urlEncoder.addSafeCharacter('/'); } - // START OF SJSAS 6231069 public Response(boolean chunkingDisabled) { outputBuffer = new OutputBuffer(); outputStream = new CoyoteOutputStream(outputBuffer); writer = createWriter(outputBuffer); urlEncoder.addSafeCharacter('/'); } - // END OF SJSAS 6231069 - - - // ----------------------------------------------------- Instance Variables - - // BEGIN S1AS 4878272 - private String detailErrorMsg; - // END S1AS 4878272 - - /** - * The date format we will use for creating date headers. - */ - protected SimpleDateFormat format = null; - - /** - * Associated context. - */ - protected Context context = null; - - protected boolean upgrade = false; // ------------------------------------------------------------- Properties @@ -136,20 +161,13 @@ public Response(boolean chunkingDisabled) { * Set whether or not to enforce scope checking of this object. */ public static void setEnforceScope(boolean enforce) { - enforceScope = enforce; - } - - /** - * Associated Catalina connector. - */ - protected Connector connector; - /** * Return the Connector through which this Request was received. */ + @Override public Connector getConnector() { return this.connector; } @@ -159,23 +177,18 @@ public Connector getConnector() { * * @param connector The new connector */ + @Override public void setConnector(Connector connector) { this.connector = connector; } - - /** - * Coyote response. - */ - protected org.glassfish.grizzly.http.server.Response coyoteResponse; - /** * Set the Coyote response. * * @param coyoteResponse The Coyote response */ public void setCoyoteResponse(org.glassfish.grizzly.http.server.Response coyoteResponse) { - this.coyoteResponse = coyoteResponse; + this.grizzlyResponse = coyoteResponse; outputBuffer.setCoyoteResponse(this); } @@ -183,127 +196,97 @@ public void setCoyoteResponse(org.glassfish.grizzly.http.server.Response coyoteR * Get the Coyote response. */ public org.glassfish.grizzly.http.server.Response getCoyoteResponse() { - return coyoteResponse; + return grizzlyResponse; } - /** * Return the Context within which this Request is being processed. */ + @Override public Context getContext() { /* - * Ideally, we would call CoyoteResponse.setContext() from - * CoyoteAdapter (the same way we call it for CoyoteRequest), and - * have getContext() return this context. However, for backwards - * compatibility with WS 7.0's NSAPIProcessor, which does not call - * CoyoteResponse.setContext(), we must delegate to the getContext() - * method of the linked request object. + * Ideally, we would call CoyoteResponse.setContext() from CoyoteAdapter (the same way we call it for CoyoteRequest), + * and have getContext() return this context. However, for backwards compatibility with WS 7.0's NSAPIProcessor, which + * does not call CoyoteResponse.setContext(), we must delegate to the getContext() method of the linked request object. */ - return request.getContext(); + return connectorRequest.getContext(); } /** - * Set the Context within which this Request is being processed. This - * must be called as soon as the appropriate Context is identified, because - * it identifies the value to be returned by getContextPath(), - * and thus enables parsing of the request URI. + * Set the Context within which this Request is being processed. This must be called as soon as the appropriate Context + * is identified, because it identifies the value to be returned by getContextPath(), and thus enables + * parsing of the request URI. * * @param context The newly associated Context */ + @Override public void setContext(Context context) { this.context = context; } - /** * The associated output buffer. */ - // START OF SJSAS 6231069 - //protected OutputBuffer outputBuffer = new OutputBuffer(); protected OutputBuffer outputBuffer; - // END OF SJSAS 6231069 /** * The associated output stream. */ - // START OF SJSAS 6231069 - /*protected CoyoteOutputStream outputStream = - new CoyoteOutputStream(outputBuffer);*/ protected CoyoteOutputStream outputStream; - // END OF SJSAS 6231069 /** * The associated writer. */ - // START OF SJSAS 6231069 - // protected CoyoteWriter writer = new CoyoteWriter(outputBuffer); protected CoyoteWriter writer; - // END OF SJSAS 6231069 - /** * The application commit flag. */ - protected boolean appCommitted = false; - + protected boolean appCommitted; /** * The included flag. */ - protected boolean included = false; - + protected boolean included; /** * The characterEncoding flag */ - private boolean isCharacterEncodingSet = false; - - /** - * The contextType flag - */ - private boolean isContentTypeSet = false; - + private boolean isCharacterEncodingSet; /** * The error flag. */ - protected boolean error = false; - + protected boolean error; /** * Using output stream flag. */ - protected boolean usingOutputStream = false; - + protected boolean usingOutputStream; /** * Using writer flag. */ - protected boolean usingWriter = false; - + protected boolean usingWriter; /** * URL encoder. */ protected UEncoder urlEncoder = new UEncoder(); - /** * Recyclable buffer to hold the redirect URL. */ - protected CharChunk redirectURLCC = new CharChunk(); - + protected CharChunk redirectURLCharChunk = new CharChunk(); // --------------------------------------------------------- Public Methods - /** - * Release all object references, and initialize instance variables, in - * preparation for reuse of this object. + * Release all object references, and initialize instance variables, in preparation for reuse of this object. */ + @Override public void recycle() { - - if (request != null && request.isAsyncStarted()) { + if (connectorRequest != null && connectorRequest.isAsyncStarted()) { return; } @@ -314,14 +297,13 @@ public void recycle() { appCommitted = false; included = false; error = false; - isContentTypeSet = false; isCharacterEncodingSet = false; detailErrorMsg = null; if (enforceScope) { - if (facade != null) { - facade.clear(); - facade = null; + if (connectorResponsefacade != null) { + connectorResponsefacade.clear(); + connectorResponsefacade = null; } if (outputStream != null) { outputStream.clear(); @@ -337,77 +319,67 @@ public void recycle() { } - // ------------------------------------------------------- Response Methods - /** * Return the number of bytes actually written to the output stream. */ + @Override public int getContentCount() { return outputBuffer.getContentWritten(); } - /** * Set the application commit flag. * * @param appCommitted The new application committed flag value */ + @Override public void setAppCommitted(boolean appCommitted) { this.appCommitted = appCommitted; } - /** * Application commit flag accessor. */ + @Override public boolean isAppCommitted() { - return this.appCommitted || isCommitted() || isSuspended() - || getContentLength() > 0 - && getContentCount() >= getContentLength(); + return appCommitted || isCommitted() || isSuspended() || getContentLength() > 0 && getContentCount() >= getContentLength(); } - /** * Return the "processing inside an include" flag. */ + @Override public boolean getIncluded() { return included; } - /** * Set the "processing inside an include" flag. * - * @param included true if we are currently inside a - * RequestDispatcher.include(), else false + * @param included true if we are currently inside a RequestDispatcher.include(), else false */ + @Override public void setIncluded(boolean included) { this.included = included; } - /** - * Return descriptive information about this Response implementation and - * the corresponding version number, in the format + * Return descriptive information about this Response implementation and the corresponding version number, in the format * <description>/<version>. */ + @Override public String getInfo() { return info; } - - /** - * The request with which this response is associated. - */ - protected Request request = null; - /** * Return the Request with which this Response is associated. */ + @Override public org.apache.catalina.Request getRequest() { - return this.request; + return connectorRequest; } /** @@ -415,33 +387,28 @@ public org.apache.catalina.Request getRequest() { * * @param request The new associated request */ + @Override public void setRequest(org.apache.catalina.Request request) { if (request instanceof Request) { - this.request = (Request) request; + this.connectorRequest = (Request) request; } } - - /** - * The facade associated with this response. - */ - protected ResponseFacade facade = null; - /** - * Return the ServletResponse for which this object - * is the facade. + * Return the ServletResponse for which this object is the facade. */ + @Override public HttpServletResponse getResponse() { - if (facade == null) { - facade = new ResponseFacade(this); + if (connectorResponsefacade == null) { + connectorResponsefacade = new ResponseFacade(this); } - return facade; + return connectorResponsefacade; } - /** * Return the output stream associated with this Response. */ + @Override public OutputStream getStream() { if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); @@ -449,81 +416,77 @@ public OutputStream getStream() { return outputStream; } - /** * Set the output stream associated with this Response. * * @param stream The new output stream */ + @Override public void setStream(OutputStream stream) { // This method is evil } - /** * Set the suspended flag. * * @param suspended The new suspended flag value */ + @Override public void setSuspended(boolean suspended) { outputBuffer.setSuspended(suspended); } - /** * Suspended flag accessor. */ + @Override public boolean isSuspended() { return outputBuffer.isSuspended(); } - /** * Set the error flag. */ + @Override public void setError() { error = true; } - /** * Error flag accessor. */ + @Override public boolean isError() { return error; } - - // BEGIN S1AS 4878272 /** * Sets detail error message. * * @param message detail error message */ + @Override public void setDetailMessage(String message) { this.detailErrorMsg = message; } - /** * Gets detail error message. * * @return the detail error message */ + @Override public String getDetailMessage() { return this.detailErrorMsg; } - // END S1AS 4878272 - /** - * Create and return a ServletOutputStream to write the content - * associated with this Response. + * Create and return a ServletOutputStream to write the content associated with this Response. * * @exception IOException if an input/output error occurs */ - public ServletOutputStream createOutputStream() - throws IOException { + @Override + public ServletOutputStream createOutputStream() throws IOException { // Probably useless if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); @@ -531,179 +494,158 @@ public ServletOutputStream createOutputStream() return outputStream; } - /** - * Perform whatever actions are required to flush and close the output - * stream or writer, in a single operation. + * Perform whatever actions are required to flush and close the output stream or writer, in a single operation. * * @exception IOException if an input/output error occurs */ - public void finishResponse() - throws IOException { - + @Override + public void finishResponse() throws IOException { // Writing leftover bytes try { outputBuffer.close(); - } catch(IOException e) { - ; - } catch(Throwable t) { - log(rb.getString(LogFacade.ERROR_DURING_FINISH_RESPONSE), t); + } catch (IOException e) { + + } catch (Throwable t) { + log(rb.getString(ERROR_DURING_FINISH_RESPONSE), t); } } - /** * Return the content length that was set or calculated for this Response. */ + @Override public int getContentLength() { - return coyoteResponse.getContentLength(); + return grizzlyResponse.getContentLength(); } - /** - * Return the content type that was set or calculated for this response, - * or null if no content type was set. + * Return the content type that was set or calculated for this response, or null if no content type was + * set. */ + @Override public String getContentType() { - return coyoteResponse.getContentType(); + return grizzlyResponse.getContentType(); } - /** - * Return a PrintWriter that can be used to render error messages, - * regardless of whether a stream or writer has already been acquired. + * Return a PrintWriter that can be used to render error messages, regardless of whether a stream or writer has already + * been acquired. * - * @return Writer which can be used for error reports. If the response is - * not an error report returned using sendError or triggered by an - * unexpected exception thrown during the servlet processing - * (and only in that case), null will be returned if the response stream - * has already been used. + * @return Writer which can be used for error reports. If the response is not an error report returned using sendError + * or triggered by an unexpected exception thrown during the servlet processing (and only in that case), null will be + * returned if the response stream has already been used. * * @exception IOException if an input/output error occurs */ + @Override public PrintWriter getReporter() throws IOException { - if (outputBuffer.isNew()) { - outputBuffer.checkConverter(); - if (writer == null) { - writer = createWriter(outputBuffer); - } - return writer; - } else { + if (!outputBuffer.isNew()) { return null; } - } + outputBuffer.checkConverter(); + if (writer == null) { + writer = createWriter(outputBuffer); + } - // ------------------------------------------------ ServletResponse Methods + return writer; + } + // ------------------------------------------------ ServletResponse Methods /** * Flush the buffer and commit this response. * * @exception IOException if an input/output error occurs */ - public void flushBuffer() - throws IOException { + @Override + public void flushBuffer() throws IOException { outputBuffer.flush(); } - /** * Return the actual buffer size used for this Response. */ + @Override public int getBufferSize() { return outputBuffer.getBufferSize(); } - /** * Return the character encoding used for this Response. */ + @Override public String getCharacterEncoding() { - return coyoteResponse.getCharacterEncoding(); + return grizzlyResponse.getCharacterEncoding(); } - /* - * Overrides the name of the character encoding used in the body - * of the request. This method must be called prior to reading - * request parameters or reading input using getReader(). + * Overrides the name of the character encoding used in the body of the request. This method must be called prior to + * reading request parameters or reading input using getReader(). * * @param charset String containing the name of the character encoding. */ + @Override public void setCharacterEncoding(String charset) { - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) - return; - // Ignore any call made after the getWriter has been invoked // The default should be used - if (usingWriter) + if (isCommitted() || included || usingWriter) { return; + } - coyoteResponse.setCharacterEncoding(charset); + grizzlyResponse.setCharacterEncoding(charset); isCharacterEncodingSet = true; } - /** * Return the servlet output stream associated with this Response. * - * @exception IllegalStateException if getWriter has - * already been called for this response + * @exception IllegalStateException if getWriter has already been called for this response * @exception IOException if an input/output error occurs */ - public ServletOutputStream getOutputStream() - throws IOException { - - if (usingWriter) - throw new IllegalStateException - (rb.getString(LogFacade.GET_WRITER_BEEN_CALLED_EXCEPTION)); + @Override + public ServletOutputStream getOutputStream() throws IOException { + if (usingWriter) { + throw new IllegalStateException(rb.getString(GET_WRITER_BEEN_CALLED_EXCEPTION)); + } usingOutputStream = true; if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } - return outputStream; + return outputStream; } - /** * Return the Locale assigned to this response. */ + @Override public Locale getLocale() { - return coyoteResponse.getLocale(); + return grizzlyResponse.getLocale(); } - /** * Return the writer associated with this Response. * - * @exception IllegalStateException if getOutputStream has - * already been called for this response + * @exception IllegalStateException if getOutputStream has already been called for this response * @exception IOException if an input/output error occurs */ - public PrintWriter getWriter() - throws IOException { - - if (usingOutputStream) + @Override + public PrintWriter getWriter() throws IOException { + if (usingOutputStream) { throw new IllegalStateException(rb.getString(LogFacade.GET_OUTPUT_STREAM_BEEN_CALLED_EXCEPTION)); + } /* - * If the response's character encoding has not been specified as - * described in getCharacterEncoding (i.e., the method - * just returns the default value ISO-8859-1), - * getWriter updates it to ISO-8859-1 - * (with the effect that a subsequent call to getContentType() will - * include a charset=ISO-8859-1 component which will also be - * reflected in the Content-Type response header, thereby satisfying - * the Servlet spec requirement that containers must communicate the - * character encoding used for the servlet response's writer to the + * If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., + * the method just returns the default value ISO-8859-1), getWriter updates it to + * ISO-8859-1 (with the effect that a subsequent call to getContentType() will include a charset=ISO-8859-1 + * component which will also be reflected in the Content-Type response header, thereby satisfying the Servlet spec + * requirement that containers must communicate the character encoding used for the servlet response's writer to the * client). */ setCharacterEncoding(getCharacterEncoding()); @@ -713,144 +655,125 @@ public PrintWriter getWriter() if (writer == null) { writer = createWriter(outputBuffer); } - return writer; + return writer; } - /** * Has the output of this response already been committed? */ + @Override public boolean isCommitted() { - return coyoteResponse.isCommitted(); + return grizzlyResponse.isCommitted(); } - /** * Clear any content written to the buffer. * - * @exception IllegalStateException if this response has already - * been committed + * @exception IllegalStateException if this response has already been committed */ + @Override public void reset() { + if (included) { + return; // Ignore any call from an included servlet + } - if (included) - return; // Ignore any call from an included servlet - - coyoteResponse.reset(); + grizzlyResponse.reset(); outputBuffer.reset(); + // reset Grizzly duplicated internal attributes - coyoteResponse.resetBuffer(true); + grizzlyResponse.resetBuffer(true); usingOutputStream = false; usingWriter = false; isCharacterEncodingSet = false; } - /** * Reset the data buffer but not any status or header information. * - * @exception IllegalStateException if the response has already - * been committed + * @exception IllegalStateException if the response has already been committed */ + @Override public void resetBuffer() { resetBuffer(false); } - /** - * Reset the data buffer and the using Writer/Stream flags but not any - * status or header information. + * Reset the data buffer and the using Writer/Stream flags but not any status or header information. * - * @param resetWriterStreamFlags true if the internal - * usingWriter, usingOutputStream, - * isCharacterEncodingSet flags should also be reset + * @param resetWriterStreamFlags true if the internal usingWriter, + * usingOutputStream, isCharacterEncodingSet flags should also be reset * - * @exception IllegalStateException if the response has already - * been committed + * @exception IllegalStateException if the response has already been committed */ + @Override public void resetBuffer(boolean resetWriterStreamFlags) { - - if (isCommitted()) - throw new IllegalStateException(rb.getString(LogFacade.CANNOT_RESET_BUFFER_EXCEPTION)); + if (isCommitted()) { + throw new IllegalStateException(rb.getString(CANNOT_RESET_BUFFER_EXCEPTION)); + } outputBuffer.reset(); - if(resetWriterStreamFlags) { + if (resetWriterStreamFlags) { usingOutputStream = false; usingWriter = false; isCharacterEncodingSet = false; } - } - /** * Set the buffer size to be used for this Response. * * @param size The new buffer size * - * @exception IllegalStateException if this method is called after - * output has been committed for this response + * @exception IllegalStateException if this method is called after output has been committed for this response */ + @Override public void setBufferSize(int size) { - - if (isCommitted() || !outputBuffer.isNew()) - throw new IllegalStateException(rb.getString(LogFacade.CANNOT_CHANGE_BUFFER_SIZE_EXCEPTION)); + if (isCommitted() || !outputBuffer.isNew()) { + throw new IllegalStateException(rb.getString(CANNOT_CHANGE_BUFFER_SIZE_EXCEPTION)); + } outputBuffer.setBufferSize(size); - } - /** * Set the content length (in bytes) for this Response. * * @param length The new content length */ + @Override public void setContentLength(int length) { - setContentLengthLong(length); - } - /** - * Sets the length of the content body in the response In HTTP servlets, - * this method sets the HTTP Content-Length header. + * Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length + * header. * * @param length The new content length */ + @Override public void setContentLengthLong(long length) { - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) - return; - - if (usingWriter) + if (isCommitted() || included || usingWriter) { return; + } - coyoteResponse.setContentLengthLong(length); - + grizzlyResponse.setContentLengthLong(length); } - /** * Set the content type for this Response. * * @param type The new content type */ + @Override public void setContentType(String type) { - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (isCommitted() || included) { return; + } // Ignore charset if getWriter() has already been called if (usingWriter) { @@ -862,7 +785,7 @@ public void setContentType(String type) { } } - coyoteResponse.setContentType(type); + grizzlyResponse.setContentType(type); // Check to see if content type contains charset if (type != null) { @@ -873,205 +796,161 @@ public void setContentType(String type) { while (index < len && Character.isWhitespace(type.charAt(index))) { index++; } - if (index+7 < len - && type.charAt(index) == 'c' - && type.charAt(index+1) == 'h' - && type.charAt(index+2) == 'a' - && type.charAt(index+3) == 'r' - && type.charAt(index+4) == 's' - && type.charAt(index+5) == 'e' - && type.charAt(index+6) == 't' - && type.charAt(index+7) == '=') { + if (index + 7 < len && + type.charAt(index) == 'c' && + type.charAt(index + 1) == 'h' && + type.charAt(index + 2) == 'a' && + type.charAt(index + 3) == 'r' && + type.charAt(index + 4) == 's' && + type.charAt(index + 5) == 'e' && + type.charAt(index + 6) == 't' && + type.charAt(index + 7) == '=') { isCharacterEncodingSet = true; } } } - - isContentTypeSet = true; } - /** - * Set the Locale that is appropriate for this response, including - * setting the appropriate character encoding. + * Set the Locale that is appropriate for this response, including setting the appropriate character encoding. * * @param locale The new locale */ + @Override public void setLocale(Locale locale) { - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (isCommitted() || included) { return; + } - coyoteResponse.setLocale(locale); + grizzlyResponse.setLocale(locale); // Ignore any call made after the getWriter has been invoked. // The default should be used - if (usingWriter) + if (usingWriter) { return; + } if (isCharacterEncodingSet) { return; } - CharsetMapper cm = getContext().getCharsetMapper(); - String charset = cm.getCharset( locale ); - if ( charset != null ){ - coyoteResponse.setCharacterEncoding(charset); + String charset = getContext().getCharsetMapper().getCharset(locale); + if (charset != null) { + grizzlyResponse.setCharacterEncoding(charset); } - } - // --------------------------------------------------- HttpResponse Methods - /** - * Return the value for the specified header, or null if this - * header has not been set. If more than one value was added for this - * name, only the first is returned; use {@link #getHeaders(String)} to - * retrieve all of them. + * Return the value for the specified header, or null if this header has not been set. If more than one + * value was added for this name, only the first is returned; use {@link #getHeaders(String)} to retrieve all of them. * * @param name Header name to look up */ + @Override public String getHeader(String name) { - return coyoteResponse.getHeader(name); + return grizzlyResponse.getHeader(name); } - /** - * @return a (possibly empty) Collection of the names - * of the headers of this response + * @return a (possibly empty) Collection of the names of the headers of this response */ + @Override public Collection getHeaderNames() { - final Collection result = new ArrayList(); - for (final String headerName : coyoteResponse.getResponse().getHeaders().names()) { - result.add(headerName); + final Collection headerNames = new ArrayList<>(); + for (String headerName : grizzlyResponse.getResponse().getHeaders().names()) { + headerNames.add(headerName); } - return result; + return headerNames; } - /** * @param name the name of the response header whose values to return * - * @return a (possibly empty) Collection of the values - * of the response header with the given name + * @return a (possibly empty) Collection of the values of the response header with the given name */ + @Override public Collection getHeaders(String name) { - final Collection result = new ArrayList(); - for (final String headerValue : coyoteResponse.getResponse().getHeaders().values(name)) { - result.add(headerValue); + final Collection headers = new ArrayList<>(); + for (String headerValue : grizzlyResponse.getResponse().getHeaders().values(name)) { + headers.add(headerValue); } - return result; + return headers; } - /** - * Return the error message that was set with sendError() - * for this Response. + * Return the error message that was set with sendError() for this Response. */ + @Override public String getMessage() { - return coyoteResponse.getMessage(); + return grizzlyResponse.getMessage(); } - /** * Return the HTTP status code associated with this Response. */ + @Override public int getStatus() { - return coyoteResponse.getStatus(); + return grizzlyResponse.getStatus(); } - /** - * Reset this response, and specify the values for the HTTP status code - * and corresponding message. + * Reset this response, and specify the values for the HTTP status code and corresponding message. * - * @exception IllegalStateException if this response has already been - * committed + * @exception IllegalStateException if this response has already been committed */ + @Override public void reset(int status, String message) { reset(); setStatus(status, message); } - // -------------------------------------------- HttpServletResponse Methods - /** - * Add the specified Cookie to those that will be included with - * this Response. + * Add the specified Cookie to those that will be included with this Response. * * @param cookie Cookie to be added */ + @Override public void addCookie(final Cookie cookie) { - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (isCommitted() || included) { return; - - /* GlassFish 898 - final StringBuilder sb = new StringBuilder(); - if (SecurityUtil.isPackageProtectionEnabled()) { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run(){ - ServerCookie.appendCookieValue - (sb, cookie.getVersion(), cookie.getName(), - cookie.getValue(), cookie.getPath(), - cookie.getDomain(), cookie.getComment(), - cookie.getMaxAge(), cookie.getSecure()); - return null; - } - }); - } else { - ServerCookie.appendCookieValue - (sb, cookie.getVersion(), cookie.getName(), cookie.getValue(), - cookie.getPath(), cookie.getDomain(), cookie.getComment(), - cookie.getMaxAge(), cookie.getSecure()); } - */ - // START GlassFish 898 + String cookieValue = getCookieString(cookie); - // END GlassFish 898 - // the header name is Set-Cookie for both "old" and v.1 ( RFC2109 ) + // The header name is Set-Cookie for both "old" and v.1 (RFC2109) // RFC2965 is not supported by browsers and the Servlet spec - // asks for 2109. - /* GlassFish 898 - addHeader("Set-Cookie", sb.toString()); - */ - // START GlassFish 898 + // asks for RFC6265 (which obsoletes both RFC2965 and RFC2109) addHeader("Set-Cookie", cookieValue); - // END GlassFish 898 } /** - * Special method for adding a session cookie as we should be overriding - * any previous + * Special method for adding a session cookie as we should be overriding any previous + * * @param cookie */ + @Override public void addSessionCookieInternal(final Cookie cookie) { - if (isCommitted()) + if (isCommitted()) { return; + } String name = cookie.getName(); final String headername = "Set-Cookie"; final String startsWith = name + "="; final String cookieString = getCookieString(cookie); boolean set = false; - MimeHeaders headers = coyoteResponse.getResponse().getHeaders(); - int n = headers.size(); - for (int i = 0; i < n; i++) { + + MimeHeaders headers = grizzlyResponse.getResponse().getHeaders(); + int headersSize = headers.size(); + for (int i = 0; i < headersSize; i++) { if (headers.getName(i).toString().equals(headername)) { if (headers.getValue(i).toString().startsWith(startsWith)) { headers.getValue(i).setString(cookieString); @@ -1079,11 +958,10 @@ public void addSessionCookieInternal(final Cookie cookie) { } } } + if (!set) { addHeader(headername, cookieString); } - - } /** @@ -1092,246 +970,173 @@ public void addSessionCookieInternal(final Cookie cookie) { * @param name Name of the header to set * @param value Date value to be set */ + @Override public void addDateHeader(String name, long value) { - - if (name == null || name.length() == 0) { - return; - } - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) { + if (name == null || name.length() == 0 || isCommitted() || included) { return; } if (format == null) { - format = new SimpleDateFormat(HTTP_RESPONSE_DATE_HEADER, - Locale.US); + format = new SimpleDateFormat(HTTP_RESPONSE_DATE_HEADER, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); } addHeader(name, FastHttpDateFormat.formatDate(value, format)); - } - /** * Add the specified header to the specified value. * * @param name Name of the header to set * @param value Value to be set */ + @Override public void addHeader(String name, String value) { - - if (name == null || name.length() == 0 || value == null) { - return; - } - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (name == null || name.length() == 0 || value == null || isCommitted() || included) { return; + } - coyoteResponse.addHeader(name, value); - + grizzlyResponse.addHeader(name, value); } - /** * Add the specified integer header to the specified value. * * @param name Name of the header to set * @param value Integer value to be set */ + @Override public void addIntHeader(String name, int value) { - - if (name == null || name.length() == 0) { - return; - } - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (name == null || name.length() == 0 || isCommitted() || included) { return; + } addHeader(name, "" + value); - } - /** * Has the specified header been set already in this response? * * @param name Name of the header to check */ + @Override public boolean containsHeader(String name) { - return coyoteResponse.containsHeader(name); + return grizzlyResponse.containsHeader(name); } - @Override public Supplier> getTrailerFields() { - return coyoteResponse.getTrailers(); + return grizzlyResponse.getTrailers(); } - @Override public void setTrailerFields(Supplier> supplier) { - coyoteResponse.setTrailers(supplier); + grizzlyResponse.setTrailers(supplier); } - /** - * Encode the session identifier associated with this response - * into the specified redirect URL, if necessary. + * Encode the session identifier associated with this response into the specified redirect URL, if necessary. * * @param url URL to be encoded */ + @Override public String encodeRedirectURL(String url) { - if (isEncodeable(toAbsolute(url))) { - String sessionVersion = null; - Map sessionVersions = - request.getSessionVersionsRequestAttribute(); - if (sessionVersions != null) { - sessionVersion = RequestUtil.createSessionVersionString( - sessionVersions); - } - return toEncoded(url, - request.getSessionInternal().getIdInternal(), - sessionVersion); - } else { + if (!isEncodeable(toAbsolute(url))) { return url; } - } + String sessionVersion = null; + Map sessionVersions = connectorRequest.getSessionVersionsRequestAttribute(); + if (sessionVersions != null) { + sessionVersion = RequestUtil.createSessionVersionString(sessionVersions); + } - /** - * Encode the session identifier associated with this response - * into the specified redirect URL, if necessary. - * - * @param url URL to be encoded - * - * @deprecated As of Version 2.1 of the Java Servlet API, use - * encodeRedirectURL() instead. - */ - public String encodeRedirectUrl(String url) { - return encodeRedirectURL(url); + return toEncoded(url, connectorRequest.getSessionInternal().getIdInternal(), sessionVersion); } - /** - * Encode the session identifier associated with this response - * into the specified URL, if necessary. + * Encode the session identifier associated with this response into the specified URL, if necessary. * * @param url URL to be encoded */ + @Override public String encodeURL(String url) { String absolute = toAbsolute(url); - if (isEncodeable(absolute)) { - // W3c spec clearly said - if (url.equalsIgnoreCase("")){ - url = absolute; - } else if (url.equals(absolute) && !hasPath(url)) { - url += '/'; - } - String sessionVersion = null; - Map sessionVersions = - request.getSessionVersionsRequestAttribute(); - if (sessionVersions != null) { - sessionVersion = RequestUtil.createSessionVersionString( - sessionVersions); - } - return toEncoded(url, - request.getSessionInternal().getIdInternal(), - sessionVersion); - } else { + if (!isEncodeable(absolute)) { return url; } - } + // W3c spec clearly said + if (url.equalsIgnoreCase("")) { + url = absolute; + } else if (url.equals(absolute) && !hasPath(url)) { + url += '/'; + } - /** - * Encode the session identifier associated with this response - * into the specified URL, if necessary. - * - * @param url URL to be encoded - * - * @deprecated As of Version 2.1 of the Java Servlet API, use - * encodeURL() instead. - */ - public String encodeUrl(String url) { - return encodeURL(url); - } + String sessionVersion = null; + Map sessionVersions = connectorRequest.getSessionVersionsRequestAttribute(); + if (sessionVersions != null) { + sessionVersion = RequestUtil.createSessionVersionString(sessionVersions); + } + return toEncoded(url, connectorRequest.getSessionInternal().getIdInternal(), sessionVersion); + } /** - * Apply URL Encoding to the given URL without adding session identifier - * et al associated to this response. + * Apply URL Encoding to the given URL without adding session identifier et al associated to this response. * * @param url URL to be encoded */ + @Override public String encode(String url) { return urlEncoder.encodeURL(url); } - /** * Send an acknowledgment of a request. * * @exception IOException if an input/output error occurs */ - public void sendAcknowledgement() - throws IOException { - - if (isCommitted()) - return; - + @Override + public void sendAcknowledgement() throws IOException { // Ignore any call from an included servlet - if (included) + if (isCommitted() || included) { return; + } - coyoteResponse.sendAcknowledgement(); - + grizzlyResponse.sendAcknowledgement(); } - /** - * Send an error response with the specified status and a - * default message. + * Send an error response with the specified status and a default message. * * @param status HTTP status code to send * - * @exception IllegalStateException if this response has - * already been committed + * @exception IllegalStateException if this response has already been committed * @exception IOException if an input/output error occurs */ - public void sendError(int status) - throws IOException { + @Override + public void sendError(int status) throws IOException { sendError(status, null); } - /** * Send an error response with the specified status and message. * * @param status HTTP status code to send * @param message Corresponding message to send * - * @exception IllegalStateException if this response has - * already been committed + * @exception IllegalStateException if this response has already been committed * @exception IOException if an input/output error occurs */ - public void sendError(int status, String message) - throws IOException { - - if (isCommitted()) - throw new IllegalStateException(rb.getString(LogFacade.CANNOT_CALL_SEND_ERROR_EXCEPTION)); + @Override + public void sendError(int status, String message) throws IOException { + if (isCommitted()) { + throw new IllegalStateException(rb.getString(CANNOT_CALL_SEND_ERROR_EXCEPTION)); + } // Ignore any call from an included servlet if (included) { @@ -1340,71 +1145,63 @@ public void sendError(int status, String message) setError(); - coyoteResponse.setStatus(status); - // use encoding in GlassFish - coyoteResponse.getResponse().setHtmlEncodingCustomReasonPhrase(false); - coyoteResponse.setDetailMessage(HtmlEntityEncoder.encodeXSS(message)); + grizzlyResponse.setStatus(status); + + // Use encoding in GlassFish + grizzlyResponse.getResponse().setHtmlEncodingCustomReasonPhrase(false); + grizzlyResponse.setDetailMessage(encodeXSS(message)); // Clear any data content that has been buffered resetBuffer(); // Cause the response to be finished (from the application perspective) setSuspended(true); - } - /** * Sends a temporary redirect to the specified redirect location URL. * * @param location Location URL to redirect to * - * @throws IllegalStateException if this response has - * already been committed + * @throws IllegalStateException if this response has already been committed * @throws IOException if an input/output error occurs */ + @Override public void sendRedirect(String location) throws IOException { sendRedirect(location, true); } - /** - * Sends a temporary or permanent redirect to the specified redirect - * location URL. + * Sends a temporary or permanent redirect to the specified redirect location URL. * * @param location Location URL to redirect to - * @param isTemporary true if the redirect is supposed to be temporary, - * false if permanent + * @param isTemporary true if the redirect is supposed to be temporary, false if permanent * - * @throws IllegalStateException if this response has - * already been committed + * @throws IllegalStateException if this response has already been committed * @throws IOException if an input/output error occurs */ - public void sendRedirect(String location, boolean isTemporary) - throws IOException { - - if (isCommitted()) - throw new IllegalStateException(rb.getString(LogFacade.CANNOT_CALL_SEND_REDIRECT_EXCEPTION)); + public void sendRedirect(String location, boolean isTemporary) throws IOException { + if (isCommitted()) { + throw new IllegalStateException(rb.getString(CANNOT_CALL_SEND_REDIRECT_EXCEPTION)); + } // Ignore any call from an included servlet - if (included) + if (included) { return; + } // Clear any data content that has been buffered resetBuffer(); // Generate a temporary redirect to the specified location try { - /* RIMOD 4642650 - String absolute = toAbsolute(location); - */ - // START RIMOD 4642650 String absolute; - if (getContext().getAllowRelativeRedirect()) + if (getContext().getAllowRelativeRedirect()) { absolute = location; - else + } else { absolute = toAbsolute(location); - // END RIMOD 4642650 + } + if (isTemporary) { setStatus(SC_MOVED_TEMPORARILY); } else { @@ -1418,7 +1215,7 @@ public void sendRedirect(String location, boolean isTemporary) setContentType("text/html"); setLocale(Locale.getDefault()); - String href = HtmlEntityEncoder.encodeXSS(absolute); + String href = encodeXSS(absolute); StringBuilder sb = new StringBuilder(150 + href.length()); sb.append("\r\n"); @@ -1446,113 +1243,90 @@ public void sendRedirect(String location, boolean isTemporary) // Cause the response to be finished (from the application perspective) setSuspended(true); - } - /** * Set the specified date header to the specified value. * * @param name Name of the header to set * @param value Date value to be set */ + @Override public void setDateHeader(String name, long value) { - - if (name == null || name.length() == 0) { - return; - } - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) { + if (name == null || name.length() == 0 || isCommitted() || included) { return; } if (format == null) { - format = new SimpleDateFormat(HTTP_RESPONSE_DATE_HEADER, - Locale.US); + format = new SimpleDateFormat(HTTP_RESPONSE_DATE_HEADER, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); } setHeader(name, FastHttpDateFormat.formatDate(value, format)); - } - /** * Set the specified header to the specified value. * * @param name Name of the header to set * @param value Value to be set */ + @Override public void setHeader(String name, String value) { - - if (name == null || name.length() == 0 || value == null) { + if (name == null || name.length() == 0 || value == null || isCommitted()) { return; } - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (included) { return; + } try { - String safeName = InputValidationUtil.getSafeHeaderName(name); - String safeValue = InputValidationUtil.getSafeHeaderValue(value); - coyoteResponse.setHeader(safeName, safeValue); + grizzlyResponse.setHeader( + getSafeHeaderName(name), + getSafeHeaderValue(value)); } catch (Exception e) { try { - coyoteResponse.sendError(403, "Forbidden"); + grizzlyResponse.sendError(403, "Forbidden"); } catch (IOException ex) { // just return } } - } - /** * Set the specified integer header to the specified value. * * @param name Name of the header to set * @param value Integer value to be set */ + @Override public void setIntHeader(String name, int value) { - - if (name == null || name.length() == 0) { - return; - } - - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (name == null || name.length() == 0 || isCommitted() || included) { return; + } setHeader(name, "" + value); - } - /** * Set the HTTP status to be returned with this response. * * @param status The new HTTP status */ + @Override public void setStatus(int status) { setStatus(status, null); } + @Override public void setError(int status, String message) { setStatus(status, message); } - /** * Set the HTTP status and message to be returned with this response. * @@ -1561,72 +1335,59 @@ public void setError(int status, String message) { * */ private void setStatus(int status, String message) { - if (isCommitted()) - return; - // Ignore any call from an included servlet - if (included) + if (isCommitted() || included) { return; + } - coyoteResponse.setStatus(status); - // use encoding in GlassFish - coyoteResponse.getResponse().setHtmlEncodingCustomReasonPhrase(false); - coyoteResponse.setDetailMessage(HtmlEntityEncoder.encodeXSS(message)); + grizzlyResponse.setStatus(status); + // Use encoding in GlassFish + grizzlyResponse.getResponse().setHtmlEncodingCustomReasonPhrase(false); + grizzlyResponse.setDetailMessage(encodeXSS(message)); } - // ------------------------------------------------------ Protected Methods - /** - * Return true if the specified URL should be encoded with - * a session identifier. This will be true if all of the following - * conditions are met: + * Return true if the specified URL should be encoded with a session identifier. This will be true if all + * of the following conditions are met: *

* * @param location Absolute URL to be validated */ protected boolean isEncodeable(final String location) { - - if (location == null) - return false; - // Is this an intra-document reference? - if (location.startsWith("#")) + if (location == null || location.startsWith("#")) { return false; + } // Are we in a valid session that is not using cookies? - final Request hreq = request; - final Session session = hreq.getSessionInternal(false); + final Session session = connectorRequest.getSessionInternal(false); if (session == null) { return false; } - if (hreq.isRequestedSessionIdFromCookie() || - getContext() != null && !getContext().isEnableURLRewriting()) { + + if (connectorRequest.isRequestedSessionIdFromCookie() || getContext() != null && !getContext().isEnableURLRewriting()) { return false; } if (SecurityUtil.isPackageProtectionEnabled()) { - return ( - AccessController.doPrivileged(new PrivilegedAction() { - + return (AccessController.doPrivileged(new PrivilegedAction() { @Override - public Boolean run(){ - return Boolean.valueOf(doIsEncodeable(hreq, session, location)); + public Boolean run() { + return Boolean.valueOf(doIsEncodeable(connectorRequest, session, location)); } })).booleanValue(); } else { - return doIsEncodeable(hreq, session, location); + return doIsEncodeable(connectorRequest, session, location); } } - private boolean doIsEncodeable(Request hreq, Session session, - String location){ + private boolean doIsEncodeable(Request hreq, Session session, String location) { // Is this a valid absolute URL? URL url = null; try { @@ -1636,26 +1397,31 @@ private boolean doIsEncodeable(Request hreq, Session session, } // Does this URL match down to (and including) the context path? - if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) - return false; - if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) + if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol()) || !hreq.getServerName().equalsIgnoreCase(url.getHost())) { return false; + } + int serverPort = hreq.getServerPort(); if (serverPort == -1) { - if ("https".equals(hreq.getScheme())) + if ("https".equals(hreq.getScheme())) { serverPort = 443; - else + } else { serverPort = 80; + } } + int urlPort = url.getPort(); if (urlPort == -1) { - if ("https".equals(url.getProtocol())) + if ("https".equals(url.getProtocol())) { urlPort = 443; - else + } else { urlPort = 80; + } } - if (serverPort != urlPort) + + if (serverPort != urlPort) { return false; + } Context ctx = getContext(); if (ctx != null) { @@ -1665,6 +1431,7 @@ private boolean doIsEncodeable(Request hreq, Session session, if (file == null || !file.startsWith(contextPath)) { return false; } + String sessionParamName = ctx.getSessionParameterName(); if (file.contains(";" + sessionParamName + "=" + session.getIdInternal())) { return false; @@ -1674,82 +1441,76 @@ private boolean doIsEncodeable(Request hreq, Session session, // This URL belongs to our web application, so it is encodeable return true; - } - /** - * Convert (if necessary) and return the absolute URL that represents the - * resource referenced by this possibly relative URL. If this URL is - * already absolute, return it unchanged. + * Convert (if necessary) and return the absolute URL that represents the resource referenced by this possibly relative + * URL. If this URL is already absolute, return it unchanged. * * @param location URL to be (possibly) converted and then returned * - * @exception IllegalArgumentException if a MalformedURLException is - * thrown when converting the relative URL to an absolute one + * @exception IllegalArgumentException if a MalformedURLException is thrown when converting the relative URL to an + * absolute one */ protected String toAbsolute(String location) { - - if (location == null) + if (location == null) { return location; + } boolean leadingSlash = location.startsWith("/"); if (location.startsWith("//")) { // Scheme relative, network-path reference in RFC 3986 - redirectURLCC.recycle(); + redirectURLCharChunk.recycle(); + // Add the scheme String scheme = getRedirectScheme(); try { - redirectURLCC.append(scheme, 0, scheme.length()); - redirectURLCC.append(':'); - redirectURLCC.append(location, 0, location.length()); - return redirectURLCC.toString(); + redirectURLCharChunk.append(scheme, 0, scheme.length()); + redirectURLCharChunk.append(':'); + redirectURLCharChunk.append(location, 0, location.length()); + + return redirectURLCharChunk.toString(); } catch (IOException e) { - IllegalArgumentException iae = - new IllegalArgumentException(location); - iae.initCause(e); - throw iae; + throw new IllegalArgumentException(location, e); } - } else if (leadingSlash || (location.indexOf("://") == -1)) { + } - redirectURLCC.recycle(); + if (leadingSlash || location.indexOf("://") == -1) { + redirectURLCharChunk.recycle(); String scheme = getRedirectScheme(); - - String name = request.getServerName(); - int port = request.getServerPort(); + String name = connectorRequest.getServerName(); + int port = connectorRequest.getServerPort(); try { - redirectURLCC.append(scheme, 0, scheme.length()); - redirectURLCC.append("://", 0, 3); - redirectURLCC.append(name, 0, name.length()); - if (scheme.equals("http") && port != 80 - || scheme.equals("https") && port != 443) { - redirectURLCC.append(':'); + redirectURLCharChunk.append(scheme, 0, scheme.length()); + redirectURLCharChunk.append("://", 0, 3); + redirectURLCharChunk.append(name, 0, name.length()); + if (scheme.equals("http") && port != 80 || scheme.equals("https") && port != 443) { + redirectURLCharChunk.append(':'); String portS = port + ""; - redirectURLCC.append(portS, 0, portS.length()); + redirectURLCharChunk.append(portS, 0, portS.length()); } + if (!leadingSlash) { - String relativePath = request.getDecodedRequestURI(); - int pos = relativePath.lastIndexOf('/'); - relativePath = relativePath.substring(0, pos); + String relativePath = connectorRequest.getDecodedRequestURI(); + relativePath = relativePath.substring(0, relativePath.lastIndexOf('/')); String encodedURI = null; final String frelativePath = relativePath; - if (SecurityUtil.isPackageProtectionEnabled() ){ - try{ - encodedURI = AccessController.doPrivileged( - new PrivilegedExceptionAction(){ - public String run() throws IOException{ - return urlEncoder.encodeURL(frelativePath); - } - }); - } catch (PrivilegedActionException pae){ - IllegalArgumentException iae = - new IllegalArgumentException(location); + if (SecurityUtil.isPackageProtectionEnabled()) { + try { + encodedURI = AccessController.doPrivileged(new PrivilegedExceptionAction() { + @Override + public String run() throws IOException { + return urlEncoder.encodeURL(frelativePath); + } + }); + } catch (PrivilegedActionException pae) { + IllegalArgumentException iae = new IllegalArgumentException(location); iae.initCause(pae.getCause()); throw iae; } @@ -1757,53 +1518,39 @@ public String run() throws IOException{ encodedURI = urlEncoder.encodeURL(relativePath); } - redirectURLCC.append(encodedURI, 0, encodedURI.length()); - redirectURLCC.append('/'); + redirectURLCharChunk.append(encodedURI, 0, encodedURI.length()); + redirectURLCharChunk.append('/'); } - redirectURLCC.append(location, 0, location.length()); - normalize(redirectURLCC); + redirectURLCharChunk.append(location, 0, location.length()); + normalize(redirectURLCharChunk); } catch (IOException e) { - IllegalArgumentException iae = - new IllegalArgumentException(location); - iae.initCause(e); - throw iae; + throw new IllegalArgumentException(location, e); } - return redirectURLCC.toString(); - - } else { - - return location; - + return redirectURLCharChunk.toString(); } + return location; } - /** * Returns the scheme for a redirect if it is not specified. */ private String getRedirectScheme() { - String scheme = request.getScheme(); + String scheme = connectorRequest.getScheme(); - // START S1AS 6170450 - if (getConnector() != null - && getConnector().getAuthPassthroughEnabled()) { + if (getConnector() != null && getConnector().getAuthPassthroughEnabled()) { ProxyHandler proxyHandler = getConnector().getProxyHandler(); - if (proxyHandler != null - && proxyHandler.getSSLKeysize(request) > 0) { + if (proxyHandler != null && proxyHandler.getSSLKeysize(connectorRequest) > 0) { scheme = "https"; } } - // END S1AS 6170450 return scheme; } - /** - * Return the specified URL with the specified session identifier - * suitably encoded. + * Return the specified URL with the specified session identifier suitably encoded. * * @param url URL to be encoded with the session id * @param sessionId Session id to be included in the encoded URL @@ -1812,74 +1559,69 @@ protected String toEncoded(String url, String sessionId) { return toEncoded(url, sessionId, null); } - /** - * Return the specified URL with the specified session identifier - * suitably encoded. + * Return the specified URL with the specified session identifier suitably encoded. * * @param url URL to be encoded with the session id * @param sessionId Session id to be included in the encoded URL * @param sessionVersion Session version to be included in the encoded URL */ - private String toEncoded(String url, String sessionId, - String sessionVersion) { - if (url == null || sessionId == null) + private String toEncoded(String url, String sessionId, String sessionVersion) { + if (url == null || sessionId == null) { return url; + } String path = url; String query = ""; String anchor = ""; + int question = url.indexOf('?'); if (question >= 0) { path = url.substring(0, question); query = url.substring(question); } + int pound = path.indexOf('#'); if (pound >= 0) { anchor = path.substring(pound); path = path.substring(0, pound); } - StringBuilder sb = new StringBuilder(path); - if( sb.length() > 0 ) { // jsessionid can't be first. + StringBuilder urlBuilder = new StringBuilder(path); + if (urlBuilder.length() > 0) { // jsessionid can't be first. StandardContext ctx = (StandardContext) getContext(); - String sessionParamName = - ctx != null ? ctx.getSessionParameterName() : - Globals.SESSION_PARAMETER_NAME; - sb.append(";" + sessionParamName + "="); - sb.append(sessionId); + String sessionParamName = ctx != null ? ctx.getSessionParameterName() : SESSION_PARAMETER_NAME; + urlBuilder.append(";" + sessionParamName + "="); + urlBuilder.append(sessionId); if (ctx != null && ctx.getJvmRoute() != null) { - sb.append('.').append(ctx.getJvmRoute()); + urlBuilder.append('.').append(ctx.getJvmRoute()); } - // START SJSAS 6337561 - String jrouteId = request.getHeader(Constants.PROXY_JROUTE); + String jrouteId = connectorRequest.getHeader(PROXY_JROUTE); if (jrouteId != null) { - sb.append(":"); - sb.append(jrouteId); + urlBuilder.append(":"); + urlBuilder.append(jrouteId); } - // END SJSAS 6337561 - final Session session = request.getSessionInternal(false); + Session session = connectorRequest.getSessionInternal(false); if (session != null) { - String replicaLocation = - (String) session.getNote(Globals.JREPLICA_SESSION_NOTE); + String replicaLocation = (String) session.getNote(JREPLICA_SESSION_NOTE); if (replicaLocation != null) { - sb.append(Globals.JREPLICA_PARAMETER); - sb.append(replicaLocation); + urlBuilder.append(JREPLICA_PARAMETER); + urlBuilder.append(replicaLocation); } } if (sessionVersion != null) { - sb.append(Globals.SESSION_VERSION_PARAMETER); - sb.append(sessionVersion); + urlBuilder.append(SESSION_VERSION_PARAMETER); + urlBuilder.append(sessionVersion); } } - sb.append(anchor); - sb.append(query); - return sb.toString(); + urlBuilder.append(anchor); + urlBuilder.append(query); + return urlBuilder.toString(); } /** @@ -1889,7 +1631,6 @@ protected CoyoteWriter createWriter(OutputBuffer outbuf) { return new CoyoteWriter(outbuf); } - // START GlassFish 898 /** * Gets the string representation of the given cookie. * @@ -1899,59 +1640,59 @@ protected CoyoteWriter createWriter(OutputBuffer outbuf) { */ protected String getCookieString(final Cookie cookie) { String cookieValue = null; - final StringBuilder sb = new StringBuilder(); - // TODO: default these values for now. update later. - final boolean versionOneStrictCompliance = CookieUtils.COOKIE_VERSION_ONE_STRICT_COMPLIANCE; - final boolean alwaysAddExpires = CookieUtils.ALWAYS_ADD_EXPIRES; - final boolean rfc6265Support = CookieUtils.RFC_6265_SUPPORT_ENABLED; if (SecurityUtil.isPackageProtectionEnabled()) { - cookieValue = AccessController.doPrivileged( - new PrivilegedAction() { - public String run(){ - CookieSerializerUtils.serializeServerCookie( - sb, versionOneStrictCompliance, rfc6265Support, - alwaysAddExpires, cookie.getName(), - cookie.getValue(), cookie.getVersion(), cookie.getPath(), - cookie.getDomain(), cookie.getComment(), - cookie.getMaxAge(), cookie.getSecure(), - cookie.isHttpOnly()); - return sb.toString(); - } - }); + cookieValue = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public String run() { + return CookieHeaderGenerator.generateHeader( + cookie.getName(), + cookie.getValue(), + cookie.getMaxAge(), + cookie.getDomain(), + cookie.getPath(), + cookie.getSecure(), + cookie.isHttpOnly(), + cookie.getAttributes()); + } + }); } else { - CookieSerializerUtils.serializeServerCookie( - sb, versionOneStrictCompliance, rfc6265Support, - alwaysAddExpires, cookie.getName(), - cookie.getValue(), cookie.getVersion(), cookie.getPath(), - cookie.getDomain(), cookie.getComment(), - cookie.getMaxAge(), cookie.getSecure(), - cookie.isHttpOnly()); - cookieValue = sb.toString(); + cookieValue = + CookieHeaderGenerator.generateHeader( + cookie.getName(), + cookie.getValue(), + cookie.getMaxAge(), + cookie.getDomain(), + cookie.getPath(), + cookie.getSecure(), + cookie.isHttpOnly(), + cookie.getAttributes()); } return cookieValue; } - // END GlassFish 898 - - // START GlassFish 896 /** - * Removes any Set-Cookie response headers whose value contains the - * string JSESSIONID + * Removes any Set-Cookie response headers whose value contains the string JSESSIONID */ public void removeSessionCookies() { String matchExpression = "^" + getContext().getSessionCookieName() + "=.*"; - coyoteResponse.getResponse().getHeaders().removeHeaderMatches("Set-Cookie", matchExpression); - matchExpression = "^" + - org.apache.catalina.authenticator.Constants.SINGLE_SIGN_ON_COOKIE + "=.*"; - coyoteResponse.getResponse().getHeaders().removeHeaderMatches("Set-Cookie", matchExpression); + grizzlyResponse.getResponse().getHeaders().removeHeaderMatches("Set-Cookie", matchExpression); + + matchExpression = "^" + org.apache.catalina.authenticator.Constants.SINGLE_SIGN_ON_COOKIE + "=.*"; + grizzlyResponse.getResponse().getHeaders().removeHeaderMatches("Set-Cookie", matchExpression); + } + + public void setUpgrade(boolean upgrade) { + this.upgrade = upgrade; + } + + void disableWriteHandler() { + outputBuffer.disableWriteHandler(); } - // END GlassFish 896 /* - * Removes /./ and /../ sequences from absolute URLs. - * Code borrowed heavily from CoyoteAdapter.normalize() + * Removes /./ and /../ sequences from absolute URLs. Code borrowed heavily from CoyoteAdapter.normalize() */ private void normalize(CharChunk cc) { // Strip query string and/or fragment first as doing it this way makes @@ -1960,10 +1701,10 @@ private void normalize(CharChunk cc) { if (truncate == -1) { truncate = cc.indexOf('#'); } + char[] truncateCC = null; if (truncate > -1) { - truncateCC = Arrays.copyOfRange(cc.getBuffer(), - cc.getStart() + truncate, cc.getEnd()); + truncateCC = Arrays.copyOfRange(cc.getBuffer(), cc.getStart() + truncate, cc.getEnd()); cc.setEnd(cc.getStart() + truncate); } @@ -1995,8 +1736,7 @@ private void normalize(CharChunk cc) { if (index < 0) { break; } - copyChars(c, start + index, start + index + 2, - end - start - index - 2); + copyChars(c, start + index, start + index + 2, end - start - index - 2); end = end - 2; cc.setEnd(end); } @@ -2014,13 +1754,12 @@ private void normalize(CharChunk cc) { throw new IllegalArgumentException(); } int index2 = -1; - for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { + for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos--) { if (c[pos] == (byte) '/') { index2 = pos; } } - copyChars(c, start + index2, start + index + 3, - end - start - index - 3); + copyChars(c, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; cc.setEnd(end); index = index2; @@ -2062,22 +1801,13 @@ private void log(String message, Throwable t) { if (connector != null && connector.getContainer() != null) { logger = connector.getContainer().getLogger(); } + String localName = "Response"; if (logger != null) { - logger.log(localName + " " + message, t, - org.apache.catalina.Logger.WARNING); + logger.log(localName + " " + message, t, WARNING); } else { log.log(Level.WARNING, localName + " " + message, t); } } - - public void setUpgrade(boolean upgrade) { - this.upgrade = upgrade; - } - - void disableWriteHandler() { - outputBuffer.disableWriteHandler(); - } } -