]> git.argeo.org Git - lgpl/argeo-commons.git/blob - argeo/cms/http/HttpServerUtils.java
Prepare next development cycle
[lgpl/argeo-commons.git] / argeo / cms / http / HttpServerUtils.java
1 package org.argeo.cms.http;
2
3 import java.net.URI;
4 import java.util.Objects;
5
6 import com.sun.net.httpserver.HttpContext;
7 import com.sun.net.httpserver.HttpExchange;
8
9 public class HttpServerUtils {
10 private final static String SLASH = "/";
11
12 private static String extractPathWithingContext(HttpContext httpContext, String fullPath, boolean startWithSlash) {
13 Objects.requireNonNull(fullPath);
14 String contextPath = httpContext.getPath();
15 if (!fullPath.startsWith(contextPath))
16 throw new IllegalArgumentException(fullPath + " does not belong to context" + contextPath);
17 String path = fullPath.substring(contextPath.length());
18 // TODO optimise?
19 if (!startWithSlash && path.startsWith(SLASH)) {
20 path = path.substring(1);
21 } else if (startWithSlash && !path.startsWith(SLASH)) {
22 path = SLASH + path;
23 }
24 return path;
25 }
26
27 /** Path within the context, NOT starting with a slash. */
28 public static String relativize(HttpExchange exchange) {
29 URI uri = exchange.getRequestURI();
30 HttpContext httpContext = exchange.getHttpContext();
31 return extractPathWithingContext(httpContext, uri.getPath(), false);
32 }
33
34 /** Path within the context, starting with a slash. */
35 public static String subPath(HttpExchange exchange) {
36 URI uri = exchange.getRequestURI();
37 HttpContext httpContext = exchange.getHttpContext();
38 return extractPathWithingContext(httpContext, uri.getPath(), true);
39 }
40
41 /** singleton */
42 private HttpServerUtils() {
43
44 }
45 }