List of usage examples for java.net URI getPath
public String getPath()
From source file:com.ibm.jaggr.core.impl.deps.DepUtils.java
/** * Maps a resource URI to a {@link DepTreeNode}. This routine finds the key * in <code>dependencies</code> that is an ancestor of * <code>requiestURI</code> and then looks for the {@link DepTreeNode} who's * name corresponds to descendant part of the URI path. * * @param requestUri/* w w w . ja va2 s.c om*/ * The URI for the resource location being sought * @param dependencies * Map of file path names to root {@link DepTreeNode}s * @return The node corresponding to <code>requestURI</code> */ static public DepTreeNode getNodeForResource(URI requestUri, Map<URI, DepTreeNode> dependencies) { DepTreeNode result = null; /* * Iterate through the map entries and find the entry who's key is the same, * or an ancestor of, the specified path */ for (Entry<URI, DepTreeNode> dependency : dependencies.entrySet()) { URI uri = dependency.getKey(); if (requestUri.getScheme() == null && uri.getScheme() != null || requestUri.getScheme() != null && !requestUri.getScheme().equals(uri.getScheme())) continue; if (requestUri.getHost() == null && uri.getHost() != null || requestUri.getHost() != null && !requestUri.getHost().equals(uri.getHost())) continue; if (requestUri.getPath().equals(uri.getPath()) || requestUri.getPath().startsWith(uri.getPath()) && (uri.getPath().endsWith("/") || requestUri.getPath().charAt(uri.getPath().length()) == '/')) //$NON-NLS-1$ { /* * Found the entry. Now find the node corresponding to the * remainder of the path. */ if (requestUri.getPath().equals(uri.getPath())) { return dependency.getValue(); } else { String modulePath = requestUri.getPath().substring(uri.getPath().length()); if (modulePath.startsWith("/")) { //$NON-NLS-1$ modulePath = modulePath.substring(1); } result = dependency.getValue().getDescendent(modulePath); } break; } } return result; }
From source file:org.jets3t.service.utils.SignatureUtils.java
/** * Build the canonical request string for a REST/HTTP request to a storage * service for the AWS Request Signature version 4. * * {@link "http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html"} * * @param uri//from ww w . java 2s . co m * @param httpMethod * the request's HTTP method just prior to sending * @param headersMap * @param requestPayloadHexSha256Hash * hex-encoded SHA256 hash of request's payload. May be null or "" in * which case the default SHA256 hash of an empty string is used. * @return canonical request string according to AWS Request Signature version 4 */ public static String awsV4BuildCanonicalRequestString(URI uri, String httpMethod, Map<String, String> headersMap, String requestPayloadHexSha256Hash) { StringBuilder canonicalStringBuf = new StringBuilder(); // HTTP Request method: GET, POST etc canonicalStringBuf.append(httpMethod).append("\n"); // Canonical URI: URI-encoded version of the absolute path String absolutePath = uri.getPath(); if (absolutePath.length() == 0) { canonicalStringBuf.append("/"); } else { canonicalStringBuf.append(SignatureUtils.awsV4EncodeURI(absolutePath, false)); } canonicalStringBuf.append("\n"); // Canonical query string String query = uri.getQuery(); if (query == null || query.length() == 0) { canonicalStringBuf.append("\n"); } else { // Parse and sort query parameters and values from query string SortedMap<String, String> sortedQueryParameters = new TreeMap<String, String>(); for (String paramPair : query.split("&")) { String[] paramNameValue = paramPair.split("="); String name = paramNameValue[0]; String value = ""; if (paramNameValue.length > 1) { value = paramNameValue[1]; } // Add parameters to sorting map, URI-encoded appropriately sortedQueryParameters.put(SignatureUtils.awsV4EncodeURI(name, true), SignatureUtils.awsV4EncodeURI(value, true)); } // Add query parameters to canonical string boolean isPriorParam = false; for (Map.Entry<String, String> entry : sortedQueryParameters.entrySet()) { if (isPriorParam) { canonicalStringBuf.append("&"); } canonicalStringBuf.append(entry.getKey()).append("=").append(entry.getValue()); isPriorParam = true; } canonicalStringBuf.append("\n"); } // Canonical Headers SortedMap<String, String> sortedHeaders = new TreeMap<String, String>(); sortedHeaders.putAll(headersMap); for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) { canonicalStringBuf.append(entry.getKey()).append(":").append(entry.getValue()).append("\n"); } canonicalStringBuf.append("\n"); // Signed headers boolean isPriorSignedHeader = false; for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) { if (isPriorSignedHeader) { canonicalStringBuf.append(";"); } canonicalStringBuf.append(entry.getKey()); isPriorSignedHeader = true; } canonicalStringBuf.append("\n"); // Hashed Payload. canonicalStringBuf.append(requestPayloadHexSha256Hash); return canonicalStringBuf.toString(); }
From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java
/** * Remove the query part from URI./*w w w . j a v a2 s .c o m*/ * * @param uri * @return URI after remove the query part. */ public static URI removeQueryPart(URI uri) { try { return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), null, null); } catch (URISyntaxException e) { Logger.error("Remove query part from uri failed.", e); return uri; } }
From source file:gate.tagger.tagme.TaggerTagMeWS.java
public static String recodeForDbp38(String uriString) { String ret;// w w w .j a va2s . co m URI uri = null; if (uriString.startsWith("http://") || uriString.startsWith("https://")) { // First try to parse the string as an URI so that any superfluous // percent-encodings can get decoded later try { uri = new URI(uriString); } catch (Exception ex) { throw new GateRuntimeException("Could not parse URI " + uriString, ex); } // now use this constructor to-recode only the necessary parts try { String path = uri.getPath(); path = path.trim(); path = path.replaceAll(" +", "_"); uri = new URI(uri.getScheme(), null, uri.getHost(), -1, path, uri.getQuery(), uri.getFragment()); } catch (Exception ex) { throw new GateRuntimeException("Could not re-construct URI: " + uri); } ret = uri.toString(); } else { if (uriString.contains("\\u")) { uriString = StringEscapeUtils.unescapeJava(uriString); } uriString = uriString.trim(); uriString = uriString.replaceAll(" +", "_"); // We need to %-encode colons, otherwise the getPath() method will return // null ... uriString = uriString.replaceAll(":", "%3A"); try { uri = new URI(uriString); // decode and prepare for minimal percent encoding uriString = uri.getPath(); } catch (URISyntaxException ex) { // do nothing: the uriString must already be ready for percent-encoding } uriString = uriString.replaceAll(" +", "_"); try { uri = new URI(null, null, null, -1, "/" + uriString, null, null); } catch (Exception ex) { throw new GateRuntimeException("Could not re-construct URI part: " + uriString); } ret = uri.toString().substring(1); } return ret; }
From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java
public static RomData getROMFrom(final String url) throws IOException { final URI uri; try {/*from w w w.ja va 2 s.c o m*/ uri = new URI(url); } catch (URISyntaxException ex) { throw new IOException("Error in URL '" + url + "\'", ex); } final String scheme = uri.getScheme(); final String userInfo = uri.getUserInfo(); final String name; final String password; if (userInfo != null) { final String[] splitted = userInfo.split("\\:"); name = splitted[0]; password = splitted[1]; } else { name = null; password = null; } final byte[] loaded; if (scheme.startsWith("http")) { loaded = loadHTTPArchive(url); } else if (scheme.startsWith("ftp")) { loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password); } else { throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']'); } final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded)); byte[] rom48 = null; byte[] rom128 = null; byte[] romTrDos = null; while (true) { final ZipArchiveEntry entry = in.getNextZipEntry(); if (entry == null) { break; } if (entry.isDirectory()) { continue; } if (ROM_48.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 48 has too big size"); } rom48 = new byte[16384]; IOUtils.readFully(in, rom48, 0, size); } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM 128TR has too big size"); } rom128 = new byte[16384]; IOUtils.readFully(in, rom128, 0, size); } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) { final int size = (int) entry.getSize(); if (size > 16384) { throw new IOException("ROM TRDOS has too big size"); } romTrDos = new byte[16384]; IOUtils.readFully(in, romTrDos, 0, size); } } if (rom48 == null) { throw new IOException(ROM_48 + " not found"); } if (rom128 == null) { throw new IOException(ROM_128TR + " not found"); } if (romTrDos == null) { throw new IOException(ROM_TRDOS + " not found"); } return new RomData(rom48, rom128, romTrDos); }
From source file:com.vmware.thinapp.common.util.AfUtil.java
/** * Checks whether the given URL string begins with a protocol (http://, * ftp://, etc.) If it does, the string is returned unchanged. If it does * not, full URL is returned and is constructed as parentUrl "/" url. * * @param url input URL string in absolute or relative form * @param parentUrl base URL to use if the given URL is in relative form * @return an absolute URL// w w w . ja va 2s . com */ public static URI relToAbs(String url, URI parentUrl) throws URISyntaxException { if (!StringUtils.hasLength(url)) { throw new URISyntaxException(url, "The input url was empty!"); } URI parent2 = new URI(parentUrl.getScheme(), parentUrl.getUserInfo(), parentUrl.getAuthority(), parentUrl.getPort(), parentUrl.getPath() + "/", // Parent URL path must end with "/" for // this to work. resolve() removes any // duplicates. parentUrl.getQuery(), parentUrl.getFragment()); return parent2.resolve(url.trim()); }
From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java
/** * Uploads files to Windows Azure Storage. * * @param run environment of build/*w ww .j a va 2s . co m*/ * @param listener logging * @param launcher env vars for remote builds * @param strAcc storage account information. * @param expContainerName container name. * @param cntPubAccess denotes if container is publicly accessible. * @param expFP File Path in ant glob syntax relative to CI tool workspace. * @param expVP Virtual Path of blob container. * @param excludeFP File Path in ant glob syntax to exclude from upload * @param uploadType upload file type * @param individualBlobs blobs from build * @param archiveBlobs blobs from build in archive files * @param cleanUpContainer if container is cleaned * @return filesUploaded number of files that are uploaded. * @throws WAStorageException throws exception */ public static int upload(Run<?, ?> run, Launcher launcher, TaskListener listener, StorageAccountInfo strAcc, String expContainerName, boolean cntPubAccess, boolean cleanUpContainer, String expFP, String expVP, String excludeFP, UploadType uploadType, List<AzureBlob> individualBlobs, List<AzureBlob> archiveBlobs, FilePath workspace) throws WAStorageException { int filesUploaded = 0; // Counter to track no. of files that are uploaded try { FilePath workspacePath = new FilePath(launcher.getChannel(), workspace.getRemote()); listener.getLogger().println(Messages.WAStoragePublisher_uploading()); CloudBlobContainer container = WAStorageClient.getBlobContainerReference(strAcc, expContainerName, true, true, cntPubAccess); // Delete previous contents if cleanup is needed if (cleanUpContainer) { deleteContents(container); } final String zipFolderName = "artifactsArchive"; final String zipName = "archive.zip"; // Make sure we exclude the tempPath from archiving. String excludesWithoutZip = "**/" + zipFolderName + "*/" + zipName; if (excludeFP != null) { excludesWithoutZip = excludeFP + "," + excludesWithoutZip; } String archiveIncludes = ""; StringTokenizer strTokens = new StringTokenizer(expFP, fpSeparator); while (strTokens.hasMoreElements()) { String fileName = strTokens.nextToken(); String embeddedVP = null; if (fileName != null && fileName.contains("::")) { int embVPSepIndex = fileName.indexOf("::"); // Separate fileName and Virtual directory name if (fileName.length() > embVPSepIndex + 1) { embeddedVP = fileName.substring(embVPSepIndex + 2, fileName.length()); if (Utils.isNullOrEmpty(embeddedVP)) { embeddedVP = null; } else if (!embeddedVP.endsWith(Constants.FWD_SLASH)) { embeddedVP = embeddedVP + Constants.FWD_SLASH; } } fileName = fileName.substring(0, embVPSepIndex); } archiveIncludes += "," + fileName; // List all the paths without the zip archives. FilePath[] paths = workspacePath.list(fileName, excludesWithoutZip); filesUploaded += paths.length; URI workspaceURI = workspacePath.toURI(); if (uploadType == UploadType.INVALID) { // no files are uploaded return 0; } if (paths.length != 0 && uploadType != UploadType.ZIP) { for (FilePath src : paths) { // Remove the workspace bit of this path URI srcURI = workspaceURI.relativize(src.toURI()); CloudBlockBlob blob; String srcPrefix = srcURI.getPath(); if (Utils.isNullOrEmpty(expVP) && Utils.isNullOrEmpty(embeddedVP)) { blob = container.getBlockBlobReference(srcPrefix); } else { String prefix = expVP; if (!Utils.isNullOrEmpty(embeddedVP)) { if (Utils.isNullOrEmpty(expVP)) { prefix = embeddedVP; } else { prefix = expVP + embeddedVP; } } blob = container.getBlockBlobReference(prefix + srcPrefix); } String uploadedFileHash = upload(listener, blob, src); individualBlobs.add(new AzureBlob(blob.getName(), blob.getUri().toString().replace("http://", "https://"), uploadedFileHash, src.length())); } } } if (filesUploaded != 0 && (uploadType != UploadType.INDIVIDUAL)) { // Create a temp dir for the upload FilePath tempPath = workspacePath.createTempDir(zipFolderName, null); Glob globScanner = new Glob(archiveIncludes, excludesWithoutZip); FilePath zipPath = tempPath.child(zipName); workspacePath.zip(zipPath.write(), globScanner); // When uploading the zip, do not add in the tempDir to the block // blob reference. String blobURI = zipPath.getName(); if (!Utils.isNullOrEmpty(expVP)) { blobURI = expVP + blobURI; } CloudBlockBlob blob = container.getBlockBlobReference(blobURI); String uploadedFileHash = upload(listener, blob, zipPath); // Make sure to note the new blob as an archive blob, // so that it can be specially marked on the azure storage page. archiveBlobs .add(new AzureBlob(blob.getName(), blob.getUri().toString().replace("http://", "https://"), uploadedFileHash, zipPath.length())); tempPath.deleteRecursive(); } } catch (StorageException | IOException | InterruptedException | URISyntaxException e) { throw new WAStorageException(e.getMessage(), e.getCause()); } return filesUploaded; }
From source file:com.microsoft.tfs.core.credentials.internal.KeychainCredentialsManager.java
/** * @param uri/*w w w .j a v a2 s . c o m*/ * the {@link URI} to use; should already have path and query parts * removed ({@link URIUtils#removePathAndQueryParts(URI)}) (must not * be <code>null</code>) */ private static KeychainInternetPassword newKeychainInternetPasswordFromURI(final URI uri) { Check.notNull(uri, "uri"); //$NON-NLS-1$ final KeychainInternetPassword keychainPassword = new KeychainInternetPassword(); /* * Compute the protocol. */ if ("http".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$ { keychainPassword.setProtocol(KeychainProtocol.HTTP); } else if ("https".equalsIgnoreCase(uri.getScheme())) //$NON-NLS-1$ { keychainPassword.setProtocol(KeychainProtocol.HTTPS); } else { keychainPassword.setProtocol(KeychainProtocol.ANY); } if (uri.getHost() != null && uri.getHost().length() > 0) { keychainPassword.setServerName(uri.getHost()); } if (uri.getPort() > 0) { keychainPassword.setPort(uri.getPort()); } if (uri.getPath() != null) { keychainPassword.setPath(uri.getPath()); } return keychainPassword; }
From source file:org.wrml.runtime.format.application.schema.json.JsonSchema.java
public static UniqueName createJsonSchemaUniqueName(final URI schemaUri) { String uniqueNameString = schemaUri.getPath(); uniqueNameString = StringUtils.stripStart(uniqueNameString, "/"); uniqueNameString = StringUtils.stripEnd(uniqueNameString, "#"); if (uniqueNameString.endsWith(".json")) { uniqueNameString = uniqueNameString.substring(0, uniqueNameString.length() - ".json".length()); }/* w w w. j ava 2s .co m*/ if (!uniqueNameString.contains("/")) { uniqueNameString = "schemas/" + uniqueNameString; } final UniqueName literalUniqueName = new UniqueName(uniqueNameString); return literalUniqueName; }
From source file:com.vmware.thinapp.common.util.AfUtil.java
/** * Given a URI, return a new URI with the query, fragment, and top level of * the path removed.// w ww. j av a 2 s . c o m * * @param uri the input URI * @return the base URI */ public static URI parentUri(URI uri) throws URISyntaxException { if (uri == null) { return null; } String protocol = uri.getScheme(); String host = uri.getHost(); // Process the port number, if any int port = uri.getPort(); // Process the path, if any String path = uri.getPath(); if (!StringUtils.hasLength(path)) { path = ""; } else { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if (!path.contains("/")) { path = ""; } else { int lastSlash = path.lastIndexOf('/'); path = path.substring(0, lastSlash); } } // Build the final URL and return it return new URI(protocol, null, host, port, path, null, null); }