下面列出了java.net.URI#normalize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static URI relativize(URI base, URI target) {
Objects.requireNonNull(base,BASE_URI_CANNOT_BE_NULL);
Objects.requireNonNull(target,TARGET_URI_CANNOT_BE_NULL);
URI nTarget = target.normalize();
if(areRelativizable(base,target)) {
URI nBase=base.normalize();
if(nBase.equals(nTarget)) {
nTarget=URI.create(EMPTY);
} else {
URI walkthrough = absoluteRelativization(nBase,nTarget);
if(!(walkthrough.getPath().startsWith(PARENT) && nTarget.getPath().isEmpty())) {
nTarget=walkthrough;
}
}
}
return nTarget;
}
public static String b(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
URI i = i(str);
if (i == null) {
return str;
}
i = i.normalize();
if (i.isOpaque()) {
return str;
}
i = a(i.getScheme(), i.getAuthority(), "/", null, null);
if (i != null) {
return i.toString();
}
return str;
}
/**
* Deletes a regular file.
*/
@Override
public boolean deleteFile(URI target) throws IOException {
target = target.normalize();
PooledS3Connection connection = null;
try {
connection = connect(target);
AmazonS3 service = connection.getService();
String[] path = getPath(target);
try {
service.deleteObject(path[0], path[1]);
return true;
} catch (AmazonClientException e) {
throw new IOException(e);
}
} finally {
disconnect(connection);
}
}
/**
* CLO-6159:
*
* @param target
* @return
*/
@Override
public boolean removeDirRecursively(URI target) throws IOException {
target = target.normalize();
PooledS3Connection connection = null;
try {
connection = connect(target);
AmazonS3 service = connection.getService();
String[] path = getPath(target);
String bucketName = path[0];
try {
if (path.length == 1) {
if (bucketName.isEmpty()) {
throw new IOException("Unable to delete root directory");
}
deleteObjects(service, service.listObjects(bucketName));
service.deleteBucket(bucketName);
} else {
String dirName = appendSlash(path[1]);
deleteObjects(service, service.listObjects(bucketName, dirName)); // no delimiter!
}
return true;
} catch (AmazonClientException e) {
throw S3Utils.getIOException(e);
}
} finally {
disconnect(connection);
}
}
public static boolean match(URIPattern[] patterns, URI uri) {
URI normalized = uri.normalize();
for (URIPattern pattern : patterns) {
if (pattern.matchNormalized(normalized)) {
return true;
}
}
return false;
}
private static String normalizeDirectory(String url) throws IllegalArgumentException {
try {
if (!url.endsWith("/")) {
return normalizeDirectory(url + '/');
}
URI norm = URI.create(url);
if (!norm.isAbsolute()) {
norm = new File(".").toURI().resolve(url);
}
norm = norm.normalize();
if (norm.isOpaque()) {
throw new IllegalArgumentException("Repository Manager URL must not be opaque: " + url);
}
String sch = norm.getScheme();
String host = norm.getAuthority();
String path = norm.getPath();
if (sch != null) {
sch = sch.toLowerCase();
}
if (host != null) {
host = host.toLowerCase();
}
return new URI(sch, host, path, null, null).toASCIIString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Creates a relative path that can be used to build a temporary
* place to store the output from a number of map-reduce tasks.
*/
public static String makeStoreTmpPath(String orig) {
Path path = new Path(orig);
URI uri = path.toUri();
uri.normalize();
String pathStr = uri.getPath();
if (path.isAbsolute()) {
return new Path("abs"+pathStr).toString();
} else {
return new Path("rel/"+pathStr).toString();
}
}
public URI relativePath(URI base, URI uri) {
URI root = base.resolve("/");
if (!root.equals(uri.resolve("/")))
// Different protocol/host/auth
return uri;
base = base.normalize();
uri = uri.normalize();
if (base.resolve("#").equals(uri.resolve("#")))
// Same path, easy
return base.relativize(uri);
if (base.isAbsolute()) {
// Ignore hostname and protocol
base = root.relativize(base).resolve(".");
uri = root.relativize(uri);
}
// Pretend they start from /
base = root.resolve(base).resolve(".");
uri = root.resolve(uri);
URI candidate = base.relativize(uri);
URI relation = DOT;
while (candidate.getPath().startsWith("/")
&& !(base.getPath().isEmpty() || base.getPath().equals("/"))) {
base = base.resolve("../");
relation = relation.resolve("../");
candidate = base.relativize(uri);
}
// Add the ../.. again
URI resolved = relation.resolve(candidate);
return resolved;
}
private String sanitizeClonePath(String clonePath) throws DevfileException {
URI uri = clonePathToURI(clonePath);
if (uri.isAbsolute()) {
throw new DevfileException(
"The clonePath must be a relative path. This seems to be an URI with a scheme: "
+ clonePath);
}
uri = uri.normalize();
String path = uri.getPath();
if (path.isEmpty()) {
// the user tried to trick us with something like "blah/.."
throw new DevfileException(
"Cloning directly into projects root is not allowed."
+ " The clonePath that resolves to empty path: "
+ clonePath);
}
if (path.startsWith("/")) {
// while technically we could allow this, because the project config contains what resembles
// an absolute path, it is better to explicitly disallow this in devfile, which is
// user-authored. Just don't give the user impression we can support absolute paths.
throw new DevfileException(
"The clonePath must be a relative. This seems to be an absolute path: " + clonePath);
}
if (path.startsWith("..")) {
// an attempt to escape the projects root, e.g. "ich/../muss/../../raus". That's a no-no.
throw new DevfileException(
"The clonePath cannot escape the projects root. Don't use .. to try and do that."
+ " The invalid path was: "
+ clonePath);
}
return path;
}
public static URI relativize(URI base, URI child) {
// Normalize paths to remove . and .. segments
base = base.normalize();
child = child.normalize();
// Split paths into segments
String[] bParts = base.getPath().split("/");
String[] cParts = child.getPath().split("/");
// Discard trailing segment of base path
if (bParts.length > 0 && !base.getPath().endsWith("/")) {
System.arraycopy(bParts, 0, bParts, 0, bParts.length - 1);
// JDK1.6+
//bParts = java.util.Arrays.copyOf(bParts, bParts.length - 1);
}
// Remove common prefix segments
int i = 0;
while (i < bParts.length && i < cParts.length && bParts[i].equals(cParts[i])) {
i++;
}
// Construct the relative path
StringBuilder sb = new StringBuilder();
for (int j = 0; j < (bParts.length - i); j++) {
sb.append("../");
}
for (int j = i; j < cParts.length; j++) {
if (j != i) {
sb.append("/");
}
sb.append(cParts[j]);
}
return URI.create(sb.toString());
}
public static boolean match(URIPattern[] patterns, URI uri) {
URI normalized = uri.normalize();
for (URIPattern pattern : patterns) {
if (pattern.matchNormalized(normalized)) {
return true;
}
}
return false;
}
public List<Info> listFiles(URI target) throws IOException {
target = target.normalize();
PooledS3Connection connection = null;
try {
connection = connect(target);
return listFiles(target, connection);
} finally {
disconnect(connection);
}
}
private static URI getUri(HttpRequest request) {
String hostName = request.getFirstHeader("host").getValue();
String requestTarget = request.getRequestLine().getUri();
URI requestUri = createUri(hostName, requestTarget);
return requestUri.normalize();
}
/**
* Construct a path from a URI
*/
public Path(URI aUri) {
uri = aUri.normalize();
}
/**
* Fixes an url according to the chosen mode.
* <p>
* Note: urls starting with an ESI variable are not rewriten.
*
* @param url
* the url to fix (can be anything found in an html page, relative, absolute, empty...)
* @param requestUrl
* The incoming request URL (could be absolute or relative to visible base url).
* @param baseUrl
* The base URL selected for this request.
* @param visibleBaseUrl
* The base URL viewed by the browser.
* @param absolute
* Should the rewritten urls contain the scheme host and port
*
* @return the fixed url.
*/
public String rewriteUrl(String url, String requestUrl, String baseUrl, String visibleBaseUrl, boolean absolute) {
// Do not rewrite Urls starting with ESI variables
// This could be improved by detecting we are in an 'esi:vars' block,
// but this would link the rewriter with ESI parsing.
if (url.startsWith("$(")) {
return url;
}
// Base url should end with /
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl + "/";
}
URI baseUri = UriUtils.createURI(baseUrl);
// If no visible url base is defined, use base url as visible base url
if (!visibleBaseUrl.endsWith("/")) {
visibleBaseUrl = visibleBaseUrl + "/";
}
URI visibleBaseUri = UriUtils.createURI(visibleBaseUrl);
// Build the absolute Uri of the request sent to the backend
URI requestUri;
if (requestUrl.startsWith(visibleBaseUrl)) {
requestUri = UriUtils.createURI(requestUrl);
} else {
requestUri = UriUtils.concatPath(baseUri, requestUrl);
}
// Interpret the url relatively to the request url (may be relative)
URI uri = UriUtils.resolve(url, requestUri);
// Normalize the path (remove . or .. if possible)
uri = uri.normalize();
// Try to relativize url to base url
URI relativeUri = baseUri.relativize(uri);
// If the url is unchanged do nothing
if (relativeUri.equals(uri)) {
LOG.debug("url kept unchanged: [{}]", url);
return url;
}
// Else rewrite replacing baseUrl by visibleBaseUrl
URI result = visibleBaseUri.resolve(relativeUri);
// If mode relative, remove all the scheme://host:port to keep only a url relative to server root (starts with
// "/")
if (!absolute) {
result = UriUtils.removeServer(result);
}
LOG.debug("url fixed: [{}] -> [{}]", url, result);
return result.toString();
}
@SuppressFBWarnings("NP_LOAD_OF_KNOWN_NULL_VALUE")
@Override
public URI copyFile(URI source, URI target) throws IOException {
target = target.normalize();
PooledS3Connection connection = null;
try {
connection = connect(target);
URI parentUri = URIUtils.getParentURI(target);
if (parentUri != null) {
Info parentInfo = info(parentUri, connection);
if (parentInfo == null) {
throw new IOException("Parent directory does not exist");
}
}
TransferManager transferManager = connection.getTransferManager();
CloverURI sourceUri = CloverURI.createSingleURI(source);
File file = null;
Exception ex1 = null;
try {
file = manager.getFile(sourceUri);
} catch (Exception ex) {
ex1 = ex;
}
if (file != null) {
return copyLocalFile(file, target, transferManager);
} else {
// conversion to File failed (remote sandbox?)
// perform regular stream copy instead
try {
try (ReadableByteChannel inputChannel = manager.getInput(sourceUri).channel()) {
// getOutputStream() takes ownership of the connection
PooledS3Connection outputStreamConnection = connection;
connection = null; // do not disconnect
try (
OutputStream output = getOutputStream(target, outputStreamConnection);
WritableByteChannel outputChannel = Channels.newChannel(output);
) {
StreamUtils.copy(inputChannel, outputChannel);
return target;
}
}
} catch (Exception ex2) {
IOException ioe = new IOException("S3 upload failed", ex2);
if (ex1 != null) {
ioe.addSuppressed(ex1);
}
throw ioe;
}
}
} finally {
disconnect(connection);
}
}
/**
* Normalizes the source identifier.
*
* @param unnormalizedName
* the unnormalized module name
* @param referrerId
* the referrer uri to resolve relative modules
* @param base
* the base uri to resolve non-relative modules
* @return the normalized source identifier {@link URI}
* @throws MalformedNameException
* if the name cannot be normalized
*/
static URI normalize(String unnormalizedName, URI referrerId, URI base) throws MalformedNameException {
URI moduleName = parse(unnormalizedName);
if (referrerId != null && isRelative(moduleName)) {
moduleName = referrerId.resolve(moduleName);
} else {
moduleName = base.resolve(moduleName);
}
return moduleName.normalize();
}
/**
* Constructs a new url source identifier.
*
* @param unnormalizedName
* the normalized module name
*/
URLSourceIdentifier(URI uri) {
this.uri = uri.normalize();
}
/**
* Sets the Uniform Resource Identifier used by the {@link Container} to resolve the appropriate {@link
* RequestHandler} for this Request. Because access to the URI is not guarded by any lock, any changes made after
* calling {@link #connect(ResponseHandler)} might never become visible to other threads.
*
* @param uri the URI to set
* @return this, to allow chaining
* @see #getUri()
*/
public Request setUri(URI uri) {
this.uri = uri.normalize();
return this;
}
/**
* Constructs a new file source identifier.
*
* @param unnormalizedName
* the normalized module name
*/
FileSourceIdentifier(URI uri) {
this.uri = uri.normalize();
}