1 package io.apicurio.registry.maven;
2
3 import java.net.URI;
4 import java.util.Locale;
5 import java.util.Objects;
6 import java.util.regex.Pattern;
7
8 public final class ReferenceUrlUtil {
9
10 private ReferenceUrlUtil() {
11 }
12
13 public static Pattern createRegistryArtifactUrlPattern(String registryUrl) {
14 URI registryUri = URI.create(registryUrl);
15 String registryPath = stripTrailingSlash(registryUri.getRawPath());
16 return Pattern.compile("^" + Pattern.quote(registryPath)
17 + "/groups/([^/]+)/artifacts/([^/]+)/versions/([^/]+)(?:/content)?$");
18 }
19
20 public static boolean isSameApicurioServer(String registryUrl, String resource) {
21 try {
22 URI registryUri = URI.create(registryUrl);
23 URI resourceUri = URI.create(resource);
24
25 return Objects.equals(lowercase(registryUri.getScheme()), lowercase(resourceUri.getScheme()))
26 && Objects.equals(lowercase(registryUri.getHost()), lowercase(resourceUri.getHost()))
27 && effectivePort(registryUri) == effectivePort(resourceUri);
28 } catch (IllegalArgumentException e) {
29 return false;
30 }
31 }
32
33 public static String decodePathSegment(String segment) {
34 try {
35 return URI.create("https://xxx/" + segment).getPath().substring(1);
36 } catch (IllegalArgumentException e) {
37 return segment;
38 }
39 }
40
41 public static String registryReferenceName(String fullReference) {
42 try {
43 URI uri = URI.create(fullReference);
44 if (uri.getRawPath() == null) {
45 return fullReference;
46 }
47
48 StringBuilder name = new StringBuilder(uri.getRawPath());
49 if (uri.getRawQuery() != null) {
50 name.append('?').append(uri.getRawQuery());
51 }
52 if (uri.getRawFragment() != null) {
53 name.append('#').append(uri.getRawFragment());
54 }
55 return name.toString();
56 } catch (IllegalArgumentException e) {
57 return fullReference;
58 }
59 }
60
61 public static boolean isAbsoluteUri(String resourceName) {
62 if (resourceName == null) {
63 return false;
64 }
65
66 try {
67 return URI.create(resourceName).isAbsolute();
68 } catch (IllegalArgumentException e) {
69 return false;
70 }
71 }
72
73 private static int effectivePort(URI uri) {
74 if (uri.getPort() != -1) {
75 return uri.getPort();
76 }
77 if ("http".equalsIgnoreCase(uri.getScheme())) {
78 return 80;
79 }
80 if ("https".equalsIgnoreCase(uri.getScheme())) {
81 return 443;
82 }
83 return -1;
84 }
85
86 private static String lowercase(String value) {
87 return value == null ? null : value.toLowerCase(Locale.ROOT);
88 }
89
90 private static String stripTrailingSlash(String path) {
91 if (path == null || path.isEmpty() || "/".equals(path)) {
92 return "";
93 }
94 while (path.endsWith("/")) {
95 path = path.substring(0, path.length() - 1);
96 }
97 return path;
98 }
99 }