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

The following examples show how to use java.net.URI#getPath() . These examples are extracted from open source projects. 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 Project: maestro-java   File: JmsOptions.java    License: Apache License 2.0 6 votes vote down vote up
public JmsOptions(final String url) {
    try {
        final URI uri = new URI(url);
        final URLQuery urlQuery = new URLQuery(uri);

        protocol = JMSProtocol.valueOf(urlQuery.getString("protocol", JMSProtocol.AMQP.name()));

        path = uri.getPath();
        type = urlQuery.getString("type", "queue");
        configuredLimitDestinations = urlQuery.getInteger("limitDestinations", 0);

        durable = urlQuery.getBoolean("durable", false);
        priority = urlQuery.getInteger("priority", 0);
        ttl = urlQuery.getLong("ttl", 0L);
        sessionMode = urlQuery.getInteger("sessionMode", Session.AUTO_ACKNOWLEDGE);
        batchAcknowledge = urlQuery.getInteger("batchAcknowledge", 0);

        connectionUrl = filterJMSURL(uri);


    } catch (Throwable t) {
        logger.warn("Something wrong happened while parsing arguments from url : {}", t.getMessage(), t);
    }
}
 
Example 2
/**
 * Container to hold AWS EC2 Instance info.
 * @param id if of the instance
 * @param uri uri to access this instance
 */
public EC2ServiceInstance(String id, URI uri) {
    this.id = id;

    String userInfo = uri.getUserInfo();
    if (StringUtils.isNotEmpty(userInfo)) {
        try {
            this.uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
            this.metadata = ConvertibleValues.of(Collections.singletonMap(
                HttpHeaders.AUTHORIZATION_INFO, userInfo
            ));
        } catch (URISyntaxException e) {
            throw new IllegalStateException("ServiceInstance URI is invalid: " + e.getMessage(), e);
        }
    } else {
        this.uri = uri;
    }
}
 
Example 3
Source Project: particle-android   File: URIUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static URI replaceQueryParameters(URI uri, String queryParams) {
    try {
        return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), queryParams, uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI/Scheme: replacing query parameters with '"+queryParams+"' for "+uri);
    }
}
 
Example 4
Source Project: opc-ua-stack   File: SocketServer.java    License: Apache License 2.0 5 votes vote down vote up
private String pathOrUrl(String endpointUrl) {
    try {
        URI uri = new URI(endpointUrl).parseServerAuthority();
        return uri.getPath();
    } catch (Throwable e) {
        logger.warn("Endpoint URL '{}' is not a valid URI: {}", e.getMessage(), e);
        return endpointUrl;
    }
}
 
Example 5
/**
 * Convert path for exception message testing purposes.
 *
 * @param path Path.
 * @return Converted path.
 * @throws Exception If failed.
 */
private Path convertPath(Path path) throws Exception {
    if (mode != PROXY)
        return path;
    else {
        URI secondaryUri = new URI(SECONDARY_URI);

        URI pathUri = path.toUri();

        return new Path(new URI(pathUri.getScheme() != null ? secondaryUri.getScheme() : null,
            pathUri.getAuthority() != null ? secondaryUri.getAuthority() : null, pathUri.getPath(), null, null));
    }
}
 
Example 6
Source Project: MCAuthLib   File: Service.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the URI of a specific endpoint of this service.
 *
 * @param endpoint Endpoint to get the URI of.
 * @param queryParams Query parameters to append to the URI.
 * @return The URI for the given endpoint.
 */
public URI getEndpointUri(String endpoint, String queryParams) {
    URI base = this.getEndpointUri(endpoint);
    try {
        return new URI(base.getScheme(), base.getAuthority(), base.getPath(), queryParams, base.getFragment());
    } catch(URISyntaxException e) {
        throw new IllegalArgumentException("Arguments resulted in invalid endpoint URI.", e);
    }
}
 
Example 7
public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method)
        throws Failure, WebApplicationException {
    if (logger.isDebugEnabled()) {

        String httpMethod = request.getHttpMethod();

        URI uri = ui.getRequestUri();

        String uriPath = uri.getPath();
        if (uri.getQuery() != null) {
            uriPath += "?" + uri.getQuery();
        }
        if (uri.getFragment() != null) {
            uriPath += "#" + uri.getFragment();
        }

        String sessionid = null;
        List<String> headerSessionId = request.getHttpHeaders().getRequestHeader("sessionid");
        if (headerSessionId != null) {
            sessionid = headerSessionId.get(0);
        }
        if (logger.isDebugEnabled()) {
            // log only in debug mode
            logger.debug(sessionid + "|" + httpMethod + "|" + uriPath);
        }
    }
    return null;
}
 
Example 8
Source Project: s3committer   File: Paths.java    License: Apache License 2.0 5 votes vote down vote up
public static String getRelativePath(Path basePath,
                                     Path fullPath) {
  // TODO: test this thoroughly
  // Use URI.create(Path#toString) to avoid URI character escape bugs
  URI relative = URI.create(basePath.toString())
      .relativize(URI.create(fullPath.toString()));
  return relative.getPath();
}
 
Example 9
static URI setQuery(URI u, String newQuery, boolean add) throws MalformedURLException {
    String query = u.getQuery();
    query = (query == null || !add) ? newQuery : query + '&' + newQuery;
    try {
        return  new URI(u.getScheme(), u.getUserInfo(), u.getHost(),
                u.getPort(), u.getPath(), query, u.getFragment());
    } catch (URISyntaxException ex) {
        MalformedURLException mex = new MalformedURLException(ex.getMessage());
        mex.initCause(ex);
        throw mex;
    }
}
 
Example 10
private int getEncodeRequestSize(URI requestURI, String[] names, String[] values) {
    int size = 0;

    // Encode Request line
    size += GET_BYTES.length;
    size += SPACE_BYTES.length;
    String path = requestURI.getPath();
    if (requestURI.getQuery() != null) {
        path += "?" + requestURI.getQuery();
    }
    size += path.getBytes().length;
    size += SPACE_BYTES.length;
    size += HTTP_1_1_BYTES.length;
    size += CRLF_BYTES.length;

    // Encode headers
    for (int i = 0; i < names.length; i++) {
        String headerName = names[i];
        String headerValue = values[i];
        if (headerName != null && headerValue != null) {
            size += headerName.getBytes().length;
            size += COLON_BYTES.length;
            size += SPACE_BYTES.length;
            size += headerValue.getBytes().length;
            size += CRLF_BYTES.length;
        }
    }

    size += CRLF_BYTES.length;

    LOG.fine("Returning a request size of " + size);
    return size;
}
 
Example 11
@Override
public boolean areCollocated(URI file1, URI file2) {
    String name1 = file1.getPath();
    String name2 = file2.getPath();
    
    return name1.endsWith(COLLOCATED_FILENAME_SUFFIX) && name2.endsWith(COLLOCATED_FILENAME_SUFFIX);
}
 
Example 12
Source Project: ParallelGit   File: GfsUriUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getRepository(URI uri) {
  checkScheme(uri);
  String path = uri.getPath();
  if(path.length() > 1 && path.endsWith("/") && !path.endsWith(":/"))
    path = path.substring(0, path.length() - 1);
  return path;
}
 
Example 13
Source Project: openjdk-8   File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

    while (is.read() != -1);
    is.close();

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example 14
Source Project: vividus   File: PageSteps.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks, that the current page has a correct relative URL <br>
 * A <b>relative URL</b> - points to a file within a web site (like <i>'about.html'</i> or <i>'/products'</i>)<br>
 * <p>
 * Actions performed at this step:
 * <ul>
 * <li>Gets the absolute URL of the current page;
 * <li>Gets relative URL from it;
 * <li>Compares it with the specified relative URL.
 * </ul>
 * <p>
 * @param relativeURL A string value of the relative URL
 */
@Then("the page has the relative URL '$relativeURL'")
public void checkPageRelativeURL(String relativeURL)
{
    URI url = UriUtils.createUri(getWebDriver().getCurrentUrl());
    // If web application under test is unavailable (no page is opened), an empty URL will be returned
    if (url.getPath() != null)
    {
        String expectedRelativeUrl = relativeURL.isEmpty() ? FORWARD_SLASH : relativeURL;
        highlightingSoftAssert.assertEquals("Page has correct relative URL",
                UriUtils.buildNewUrl(getWebDriver().getCurrentUrl(), expectedRelativeUrl), url);
        return;
    }
    highlightingSoftAssert.recordFailedAssertion("URL path component is null");
}
 
Example 15
private static URI removeQueryFromURI(final URI uri) {
  try {
    return new URI(
        uri.getScheme(),
        uri.getUserInfo(),
        uri.getHost(),
        uri.getPort(),
        uri.getPath(),
        null,
        uri.getFragment());
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example 16
Source Project: Bytecoder   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies whether the file resource exists.
 *
 * @param uri the URI to locate the resource
 * @param openJarFile a flag to indicate whether a JAR file should be
 * opened. This operation may be expensive.
 * @return true if the resource exists, false otherwise.
 */
static boolean isFileUriExist(URI uri, boolean openJarFile) {
    if (uri != null && uri.isAbsolute()) {
        if (null != uri.getScheme()) {
            switch (uri.getScheme()) {
                case SCHEME_FILE:
                    String path = uri.getPath();
                    File f1 = new File(path);
                    if (f1.isFile()) {
                        return true;
                    }
                    break;
                case SCHEME_JAR:
                    String tempUri = uri.toString();
                    int pos = tempUri.indexOf("!");
                    if (pos < 0) {
                        return false;
                    }
                    if (openJarFile) {
                        String jarFile = tempUri.substring(SCHEME_JARFILE.length(), pos);
                        String entryName = tempUri.substring(pos + 2);
                        try {
                            JarFile jf = new JarFile(jarFile);
                            JarEntry je = jf.getJarEntry(entryName);
                            if (je != null) {
                                return true;
                            }
                        } catch (IOException ex) {
                            return false;
                        }
                    } else {
                        return true;
                    }
                    break;
            }
        }
    }
    return false;
}
 
Example 17
Source Project: boon   File: IO.java    License: Apache License 2.0 5 votes vote down vote up
public static Path uriToPath( URI uri ) {
    Path thePath = null;
    if ( Sys.isWindows() ) {
        String newPath = uri.getPath();
        if ( newPath.startsWith( "/C:" ) ) {
            newPath = slc( newPath, 3 );
        }
        thePath = FileSystems.getDefault().getPath( newPath );
    } else {
        thePath = FileSystems.getDefault().getPath( uri.getPath() );
    }
    return thePath;
}
 
Example 18
@Override
public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) {
    VolumeObjectTO srcVolume = (VolumeObjectTO)cmd.getSrcTO();
    VolumeObjectTO destVolume = (VolumeObjectTO)cmd.getDestTO();
    VmwareContext context = hostService.getServiceContext(cmd);
    try {

        NfsTO srcStore = (NfsTO)srcVolume.getDataStore();
        DataStoreTO destStore = destVolume.getDataStore();

        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        String uuid = destStore.getUuid();

        ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, uuid);
        if (morDatastore == null) {
            URI uri = new URI(destStore.getUrl());

            morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), destStore.getUuid().replace("-", ""));

            if (morDatastore == null) {
                throw new Exception("Unable to mount storage pool on host. storeUrl: " + uri.getHost() + ":/" + uri.getPath());
            }
        }

        Pair<String, String> result = copyVolumeFromSecStorage(hyperHost, srcVolume.getPath(), new DatastoreMO(context, morDatastore), srcStore.getUrl(), (long)cmd.getWait() * 1000, _nfsVersion);
        deleteVolumeDirOnSecondaryStorage(result.first(), srcStore.getUrl(), _nfsVersion);
        VolumeObjectTO newVolume = new VolumeObjectTO();
        newVolume.setPath(result.second());
        return new CopyCmdAnswer(newVolume);
    } catch (Throwable t) {
        if (t instanceof RemoteException) {
            hostService.invalidateServiceContext(context);
        }

        String msg = "Unable to execute CopyVolumeCommand due to exception";
        s_logger.error(msg, t);
        return new CopyCmdAnswer("copy volume secondary to primary failed due to exception: " + VmwareHelper.getExceptionMessage(t));
    }

}
 
Example 19
private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
    String bscheme = null;
    String bauthority = null;
    String bpath = "";
    String bquery = null;

    // pre-parse the baseURI
    if (baseURI != null) {
        if (baseURI.endsWith("..")) {
            baseURI = baseURI + "/";
        }
        URI base = new URI(baseURI);
        bscheme = base.getScheme();
        bauthority = base.getAuthority();
        bpath = base.getPath();
        bquery = base.getQuery();
    }

    URI r = new URI(relativeURI);
    String rscheme = r.getScheme();
    String rauthority = r.getAuthority();
    String rpath = r.getPath();
    String rquery = r.getQuery();

    String tscheme, tauthority, tpath, tquery;
    if (rscheme != null && rscheme.equals(bscheme)) {
        rscheme = null;
    }
    if (rscheme != null) {
        tscheme = rscheme;
        tauthority = rauthority;
        tpath = removeDotSegments(rpath);
        tquery = rquery;
    } else {
        if (rauthority != null) {
            tauthority = rauthority;
            tpath = removeDotSegments(rpath);
            tquery = rquery;
        } else {
            if (rpath.length() == 0) {
                tpath = bpath;
                if (rquery != null) {
                    tquery = rquery;
                } else {
                    tquery = bquery;
                }
            } else {
                if (rpath.startsWith("/")) {
                    tpath = removeDotSegments(rpath);
                } else {
                    if (bauthority != null && bpath.length() == 0) {
                        tpath = "/" + rpath;
                    } else {
                        int last = bpath.lastIndexOf('/');
                        if (last == -1) {
                            tpath = rpath;
                        } else {
                            tpath = bpath.substring(0, last+1) + rpath;
                        }
                    }
                    tpath = removeDotSegments(tpath);
                }
                tquery = rquery;
            }
            tauthority = bauthority;
        }
        tscheme = bscheme;
    }
    return new URI(tscheme, tauthority, tpath, tquery, null).toString();
}
 
Example 20
public static String resolveRelativeUri(URL base, final String value0) {
	final String value = value0.replaceAll("^\\s+", "");

	try {
		final URI uri = new URI(value);
		final UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri);
		UriComponents components = null;

		if (uri.getScheme() == null) {
			builder.scheme(base.getProtocol());
		}

		if (uri.getHost() == null && uri.getPath() != null) {
			builder.host(base.getHost()).port(base.getPort());

			String path;

			if (value.startsWith(base.getHost() + "/")) {
				// Special case when URI starts with a hostname but has no schema
				//  so that hostname is treated as a leading part of a path.
				// It is possible to resolve that ambiguity when a base URL has the
				//  same hostname.
				path = uri.getPath().substring(base.getHost().length() - 1);
			} else {
				if (value.startsWith("/")) {
					// Base path is ignored when a URI starts with a slash
					path = uri.getPath();
				} else {
					if (base.getPath() != null) {
						path = base.getPath() + "/" + uri.getPath();
					} else {
						path = uri.getPath();
					}
				}
			}

			Deque<String> segments = new ArrayDeque<>();
			for (String segment : path.split("/")) {
				switch (segment) {
					case "":
					case ".":
						// Remove duplicating slashes and redundant "." operator
						break;

					case "..":
						// Remove previous segment if possible or append another ".." operator
						String last = segments.peekLast();
						if (last != null && !last.equals("..")) {
							segments.removeLast();
						} else {
							segments.addLast(segment);
						}
						break;

					default:
						segments.addLast(segment);
						break;
				}
			}
			components = builder.replacePath("/" + StringUtils.join(segments, "/")).build();
		}

		if (components != null) {
			return components.toString();
		}
	} catch (URISyntaxException e) {
		logger.error("Error occurred: " + e.getMessage(), e);
	}
	return value;
}