URIUtils.java
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* org.apache.commons.lang.StringUtils
* org.apache.sling.api.request.RequestPathInfo
*/
package com.adobe.granite.rest.utils;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.request.RequestPathInfo;
public final class URIUtils {
private URIUtils() {
}
public static String urlEncodePath(String toEncode) {
try {
return URLEncoder.encode(toEncode, "UTF-8").replace("%2F", "/");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to encode URL: default charset is unexpected", e);
}
}
public static String relativize(RequestPathInfo requestPathInfo, String resourcePath) {
String lastSegment;
URI relative;
URI base;
if (requestPathInfo == null) {
throw new IllegalArgumentException("RequestPathInfo cannot be null");
}
if (resourcePath == null) {
throw new IllegalArgumentException("Resource URI cannot be null");
}
String requestPath = requestPathInfo.getResourcePath();
String uri = resourcePath;
if (requestPath.equals(resourcePath)) {
String lastSegment2 = resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
if (requestPathInfo.getSelectorString() != null) {
lastSegment2 = lastSegment2 + "." + requestPathInfo.getSelectorString();
}
return lastSegment2;
}
if (URIUtils.isParent(requestPath, resourcePath)) {
String pathTraversal = "";
String diff = requestPath.replaceFirst(resourcePath, "");
lastSegment = resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
for (int i = 0; i < StringUtils.countMatches((String)diff, (String)"/"); ++i) {
pathTraversal = pathTraversal + "../";
}
if (!pathTraversal.isEmpty()) {
return pathTraversal + lastSegment;
}
}
if (!(relative = (base = URI.create(requestPath)).relativize(URI.create(resourcePath))).toString().isEmpty()) {
if (relative.toString().equals(resourcePath)) {
return resourcePath;
}
lastSegment = requestPath.substring(requestPath.lastIndexOf("/") + 1);
uri = lastSegment + "/" + relative.toString();
}
return uri;
}
private static boolean isParent(String requestPath, String resourcePath) {
int selectorIdx = requestPath.indexOf(".");
if (selectorIdx > -1) {
requestPath = requestPath.substring(0, selectorIdx);
}
boolean isIndexOf = requestPath.indexOf(resourcePath) > -1;
boolean isShorter = requestPath.length() > resourcePath.length();
return isIndexOf && isShorter;
}
}