X-Git-Url: https://git.argeo.org/?a=blobdiff_plain;f=org.argeo.util%2Fsrc%2Forg%2Fargeo%2Futil%2Fhttp%2FHttpServerUtils.java;h=9127d2c216dcd074f14721b4ab3d34f5660fc791;hb=1d6840195189cbdbf632ca2800b6179d3b6349df;hp=6c6e88414546823827615eda550d6255ab19ed6f;hpb=6832a0807e45e70c23b22598874807a3a9373475;p=lgpl%2Fargeo-commons.git diff --git a/org.argeo.util/src/org/argeo/util/http/HttpServerUtils.java b/org.argeo.util/src/org/argeo/util/http/HttpServerUtils.java index 6c6e88414..9127d2c21 100644 --- a/org.argeo.util/src/org/argeo/util/http/HttpServerUtils.java +++ b/org.argeo.util/src/org/argeo/util/http/HttpServerUtils.java @@ -7,22 +7,35 @@ import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpExchange; public class HttpServerUtils { + private final static String SLASH = "/"; - public static String relativize(HttpContext httpContext, String path) { - Objects.requireNonNull(path); - if (!path.startsWith(httpContext.getPath())) - throw new IllegalArgumentException(path + " does not belong to context" + httpContext.getPath()); - String relativePath = path.substring(httpContext.getPath().length()); + private static String extractPathWithingContext(HttpContext httpContext, String fullPath, boolean startWithSlash) { + Objects.requireNonNull(fullPath); + String contextPath = httpContext.getPath(); + if (!fullPath.startsWith(contextPath)) + throw new IllegalArgumentException(fullPath + " does not belong to context" + contextPath); + String path = fullPath.substring(contextPath.length()); // TODO optimise? - if (relativePath.startsWith("/")) - relativePath = relativePath.substring(1); - return relativePath; + if (!startWithSlash && path.startsWith(SLASH)) { + path = path.substring(1); + } else if (startWithSlash && !path.startsWith(SLASH)) { + path = SLASH + path; + } + return path; } + /** Path within the context, NOT starting with a slash. */ public static String relativize(HttpExchange exchange) { URI uri = exchange.getRequestURI(); HttpContext httpContext = exchange.getHttpContext(); - return relativize(httpContext, uri.getPath()); + return extractPathWithingContext(httpContext, uri.getPath(), false); + } + + /** Path within the context, starting with a slash. */ + public static String subPath(HttpExchange exchange) { + URI uri = exchange.getRequestURI(); + HttpContext httpContext = exchange.getHttpContext(); + return extractPathWithingContext(httpContext, uri.getPath(), true); } /** singleton */