]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/http/server/HttpServerUtils.java
Improve ACR attribute typing.
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / http / server / HttpServerUtils.java
1 package org.argeo.cms.http.server;
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 /** HTTP utilities on the server-side. */
10 public class HttpServerUtils {
11 private final static String SLASH = "/";
12
13 private static String extractPathWithingContext(HttpContext httpContext, String fullPath, boolean startWithSlash) {
14 Objects.requireNonNull(fullPath);
15 String contextPath = httpContext.getPath();
16 if (!fullPath.startsWith(contextPath))
17 throw new IllegalArgumentException(fullPath + " does not belong to context" + contextPath);
18 String path = fullPath.substring(contextPath.length());
19 // TODO optimise?
20 if (!startWithSlash && path.startsWith(SLASH)) {
21 path = path.substring(1);
22 } else if (startWithSlash && !path.startsWith(SLASH)) {
23 path = SLASH + path;
24 }
25 return path;
26 }
27
28 /** Path within the context, NOT starting with a slash. */
29 public static String relativize(HttpExchange exchange) {
30 URI uri = exchange.getRequestURI();
31 HttpContext httpContext = exchange.getHttpContext();
32 return extractPathWithingContext(httpContext, uri.getPath(), false);
33 }
34
35 /** Path within the context, starting with a slash. */
36 public static String subPath(HttpExchange exchange) {
37 URI uri = exchange.getRequestURI();
38 HttpContext httpContext = exchange.getHttpContext();
39 return extractPathWithingContext(httpContext, uri.getPath(), true);
40 }
41
42 /** singleton */
43 private HttpServerUtils() {
44
45 }
46 }