From 5b4c05777c78245f91cf80eb7d6748d3d4a84a9c Mon Sep 17 00:00:00 2001 From: Sam Berlin Date: Fri, 14 Apr 2023 13:26:46 -0700 Subject: [PATCH] prevent NullPointerException if contextPath is null Fixes #1656 Fixes #1655 PiperOrigin-RevId: 524371974 --- .../src/com/google/inject/servlet/ServletDefinition.java | 9 ++++++--- .../inject/servlet/ServletDefinitionPathsTest.java | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/extensions/servlet/src/com/google/inject/servlet/ServletDefinition.java b/extensions/servlet/src/com/google/inject/servlet/ServletDefinition.java index 68e134b1bb..bd27d818d6 100644 --- a/extensions/servlet/src/com/google/inject/servlet/ServletDefinition.java +++ b/extensions/servlet/src/com/google/inject/servlet/ServletDefinition.java @@ -212,12 +212,15 @@ public String getPathInfo() { String servletPath = getServletPath(); int servletPathLength = servletPath.length(); String requestUri = getRequestURI(); - pathInfo = requestUri.substring(getContextPath().length()).replaceAll("[/]{2,}", "/"); + String contextPath = getContextPath(); + // https://github.com/google/guice/issues/1655, contextPath is occasionally null + int contextPathLength = contextPath != null ? contextPath.length() : 0; + pathInfo = requestUri.substring(contextPathLength).replaceAll("[/]{2,}", "/"); // See: https://github.com/google/guice/issues/372 if (pathInfo.startsWith(servletPath)) { pathInfo = pathInfo.substring(servletPathLength); - // Corner case: when servlet path & request path match exactly (without trailing '/'), - // then pathinfo is null. + // Corner case: when servlet path & request path match exactly + // (without trailing '/'), then pathinfo is null. if (pathInfo.isEmpty() && servletPathLength > 0) { pathInfo = null; } else { diff --git a/extensions/servlet/test/com/google/inject/servlet/ServletDefinitionPathsTest.java b/extensions/servlet/test/com/google/inject/servlet/ServletDefinitionPathsTest.java index db834ba5a7..4994acaca0 100644 --- a/extensions/servlet/test/com/google/inject/servlet/ServletDefinitionPathsTest.java +++ b/extensions/servlet/test/com/google/inject/servlet/ServletDefinitionPathsTest.java @@ -136,6 +136,9 @@ public final void testPathInfoWithServletStyleMatching() throws IOException, Ser "/path", "/*", "/a file with spaces in name.html", ""); pathInfoWithServletStyleMatching( "/path/Tam%C3%A1s%20nem%20m%C3%A1s.html", "/path", "/*", "/Tamás nem más.html", ""); + + // see https://github.com/google/guice/issues/1655 + pathInfoWithServletStyleMatching("/index.html", null, "/*", "/index.html", ""); } private void pathInfoWithServletStyleMatching(