Newer
Older
/*
* This file is part of vospace-rest
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.oats.vospace;
import it.inaf.oats.vospace.exception.InvalidURIException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import net.ivoa.xml.vospace.v2.Node;
public class URIUtils {
// It's different from the one in NodeUtils!
// Slashes are treated separately
private static final Pattern FORBIDDEN_CHARS = Pattern.compile("[\\x00\\x08\\x0B\\x0C\\x0E-\\x1F" + Pattern.quote("<>?\":\\|'`*") + "]");
Nicola Fulvio Calabria
committed
private static final String SCHEME = "vos";
public static String returnURIFromVosPath(String vosPath, String authority)
throws URISyntaxException {
URI uri = new URI(
SCHEME,
authority,
vosPath,
null,
null
);
return uri.toASCIIString();
}
public static String returnVosPathFromNodeURI(Node myNode, String authority) {
return returnVosPathFromNodeURI(myNode.getUri(), authority);
}
// This method validates the URI too
public static String returnVosPathFromNodeURI(String nodeURI, String authority) {
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
try {
URI uri = new URI(nodeURI);
// Check scheme
if (!uri.isAbsolute()
|| uri.isOpaque()
|| !uri.getRawSchemeSpecificPart().startsWith("//")
|| !uri.getScheme().equalsIgnoreCase(SCHEME)) {
throw new InvalidURIException(nodeURI);
}
// Check authority
if (!uri.getAuthority().replace("~", "!").equals(authority)) {
throw new InvalidURIException(nodeURI);
}
// Check path
String rawPath = uri.getRawPath();
// Check if raw Path is null or contains percent encoded slashes or multiple
// separators
if (rawPath == null
|| rawPath.contains("//")
|| rawPath.contains("%2F")
|| rawPath.contains("%2f")) {
throw new InvalidURIException(nodeURI);
}
resultPath = uri.getPath();
if (resultPath.isBlank()
|| FORBIDDEN_CHARS.matcher(resultPath).find()
|| (!resultPath.equals("/") && resultPath.endsWith("/"))) {
throw new InvalidURIException(nodeURI);
}
} catch (URISyntaxException e) {
throw new InvalidURIException(nodeURI);
}
return resultPath;