Java Code Examples for java.net.URI#normalize()

The following examples show how to use java.net.URI#normalize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URIUtils.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: jr.java    From letv with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: PrimitiveS3OperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
Source File: PrimitiveS3OperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
	}
}
 
Example 5
Source File: PrimitiveS3OperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 6
Source File: URIPattern.java    From crate with Apache License 2.0 5 votes vote down vote up
public static boolean match(URIPattern[] patterns, URI uri) {
    URI normalized = uri.normalize();
    for (URIPattern pattern : patterns) {
        if (pattern.matchNormalized(normalized)) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: URIPattern.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static boolean match(URIPattern[] patterns, URI uri) {
    URI normalized = uri.normalize();
    for (URIPattern pattern : patterns) {
        if (pattern.matchNormalized(normalized)) {
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: RepositoryProvider.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
	}
}
 
Example 9
Source File: PlanHelper.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
Source File: LangUtils.java    From pixymeta-android with Eclipse Public License 1.0 5 votes vote down vote up
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());
}
 
Example 11
Source File: ProjectConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: URITools.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: Path.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a path from a URI
 */
public Path(URI aUri) {
  uri = aUri.normalize();
}
 
Example 14
Source File: PrimitiveS3CopyOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
@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);
	}
}
 
Example 15
Source File: UrlRewriter.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 16
Source File: AwsSigner4Request.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
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();
}
 
Example 17
Source File: SourceIdentifiers.java    From es6draft with MIT License 3 votes vote down vote up
/**
 * 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();
}
 
Example 18
Source File: Request.java    From vespa with Apache License 2.0 2 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: FileSourceIdentifier.java    From es6draft with MIT License 2 votes vote down vote up
/**
 * Constructs a new file source identifier.
 * 
 * @param unnormalizedName
 *            the normalized module name
 */
FileSourceIdentifier(URI uri) {
    this.uri = uri.normalize();
}
 
Example 20
Source File: URLSourceIdentifier.java    From es6draft with MIT License 2 votes vote down vote up
/**
 * Constructs a new url source identifier.
 * 
 * @param unnormalizedName
 *            the normalized module name
 */
URLSourceIdentifier(URI uri) {
    this.uri = uri.normalize();
}