X-Git-Url: https://git.argeo.org/?a=blobdiff_plain;ds=sidebyside;f=org.argeo.cms%2Fsrc%2Forg%2Fargeo%2Fcms%2Fhttp%2FHttpServerUtils.java;fp=org.argeo.cms%2Fsrc%2Forg%2Fargeo%2Fcms%2Fhttp%2FHttpServerUtils.java;h=fc04fbfaa7cff5e01d835b20507a08e8b53678a0;hb=54df376a9c2dd458a82eaa09bfbb718fe699dd0d;hp=0000000000000000000000000000000000000000;hpb=3c1cdc594d954520b14646102b366290bdad58c7;p=lgpl%2Fargeo-commons.git diff --git a/org.argeo.cms/src/org/argeo/cms/http/HttpServerUtils.java b/org.argeo.cms/src/org/argeo/cms/http/HttpServerUtils.java new file mode 100644 index 000000000..fc04fbfaa --- /dev/null +++ b/org.argeo.cms/src/org/argeo/cms/http/HttpServerUtils.java @@ -0,0 +1,45 @@ +package org.argeo.cms.http; + +import java.net.URI; +import java.util.Objects; + +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpExchange; + +public class HttpServerUtils { + private final static String SLASH = "/"; + + 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 (!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 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 */ + private HttpServerUtils() { + + } +}