java.net.URI#getPath ( )源码实例Demo

下面列出了java.net.URI#getPath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: maestro-java   文件: JmsOptions.java
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);
    }
}
 
源代码2 项目: micronaut-aws   文件: EC2ServiceInstance.java
/**
 * 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;
    }
}
 
源代码3 项目: particle-android   文件: URIUtils.java
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);
    }
}
 
源代码4 项目: opc-ua-stack   文件: SocketServer.java
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;
    }
}
 
/**
 * 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));
    }
}
 
源代码6 项目: MCAuthLib   文件: Service.java
/**
 * 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);
    }
}
 
源代码7 项目: scheduling   文件: LoggingInterceptor.java
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;
}
 
源代码8 项目: s3committer   文件: Paths.java
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();
}
 
源代码9 项目: proarc   文件: AlephXServer.java
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;
    }
}
 
源代码10 项目: particle-android   文件: WebSocketDelegateImpl.java
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;
}
 
源代码11 项目: netbeans   文件: TestVCSCollocationQuery.java
@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);
}
 
源代码12 项目: ParallelGit   文件: GfsUriUtils.java
@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;
}
 
源代码13 项目: openjdk-8   文件: Basic.java
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();
}
 
源代码14 项目: vividus   文件: PageSteps.java
/**
 * 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");
}
 
源代码15 项目: besu   文件: PermissioningConfigurationValidator.java
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);
  }
}
 
源代码16 项目: Bytecoder   文件: Util.java
/**
 * 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;
}
 
源代码17 项目: boon   文件: IO.java
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;
}
 
源代码18 项目: cloudstack   文件: VmwareStorageProcessor.java
@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));
    }

}
 
源代码19 项目: jdk8u-jdk   文件: Canonicalizer11.java
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();
}
 
源代码20 项目: openemm   文件: HttpUtils.java
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;
}