java.net.URL.getProtocol()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(477)

本文整理了Java中java.net.URL.getProtocol()方法的一些代码示例,展示了URL.getProtocol()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。URL.getProtocol()方法的具体详情如下:
包路径:java.net.URL
类名称:URL
方法名:getProtocol

URL.getProtocol介绍

[英]Returns the protocol of this URL like "http" or "file". This is also known as the scheme. The returned string is lower case.
[中]返回此URL的协议,如“http”或“文件”。这也被称为计划。返回的字符串是小写的。

代码示例

代码示例来源:origin: spring-projects/spring-framework

/**
 * Determine whether the given URL points to a jar file itself,
 * that is, has protocol "file" and ends with the ".jar" extension.
 * @param url the URL to check
 * @return whether the URL has been identified as a JAR file URL
 * @since 4.1
 */
public static boolean isJarFileURL(URL url) {
  return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&
      url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));
}

代码示例来源:origin: google/guava

@VisibleForTesting
 static File toFile(URL url) {
  checkArgument(url.getProtocol().equals("file"));
  try {
   return new File(url.toURI()); // Accepts escaped characters like %20.
  } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars.
   return new File(url.getPath()); // Accepts non-escaped chars like space.
  }
 }
}

代码示例来源:origin: Netflix/eureka

public DefaultEndpoint(String serviceUrl) {
  this.serviceUrl = serviceUrl;
  try {
    URL url = new URL(serviceUrl);
    this.networkAddress = url.getHost();
    this.port = url.getPort();
    this.isSecure = "https".equals(url.getProtocol());
    this.relativeUri = url.getPath();
  } catch (Exception e) {
    throw new IllegalArgumentException("Malformed serviceUrl: " + serviceUrl);
  }
}

代码示例来源:origin: jfinal/jfinal

protected void processIsInJarAndlastModified() {
  if ("file".equalsIgnoreCase(url.getProtocol())) {
    isInJar = false;
    lastModified = new File(url.getFile()).lastModified();
  } else {	
    isInJar = true;
    lastModified = -1;
  }
}

代码示例来源:origin: xalan/xalan

/**
 * Returns the time-stamp for a document's last update
 */
private final long getLastModified(String uri) {
try {
  URL url = new URL(uri);
  URLConnection connection = url.openConnection();
  long timestamp = connection.getLastModified();
  // Check for a "file:" URI (courtesy of Brian Ewins)
  if (timestamp == 0){ // get 0 for local URI
    if ("file".equals(url.getProtocol())){
      File localfile = new File(URLDecoder.decode(url.getFile()));
      timestamp = localfile.lastModified();
    }
  }
  return(timestamp);
}
// Brutal handling of all exceptions
catch (Exception e) {
  return(System.currentTimeMillis());
}
}

代码示例来源:origin: jenkinsci/jenkins

private static String getUnmigrationCommandLine(File jenkinsHome) {
  StringBuilder cp = new StringBuilder();
  for (Class<?> c : new Class<?>[] {RunIdMigrator.class, /* TODO how to calculate transitive dependencies automatically? */Charsets.class, WriterOutputStream.class, BuildException.class, FastDateFormat.class}) {
    URL location = c.getProtectionDomain().getCodeSource().getLocation();
    String locationS = location.toString();
    if (location.getProtocol().equals("file")) {
      try {
        locationS = new File(location.toURI()).getAbsolutePath();
      } catch (URISyntaxException x) {
        // never mind
      }
    }
    if (cp.length() > 0) {
      cp.append(File.pathSeparator);
    }
    cp.append(locationS);
  }
  return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome);
}

代码示例来源:origin: stagemonitor/stagemonitor

public static File getFile(String classPathLocation) throws IOException, URISyntaxException {
    URL resource = PropertyFileConfigurationSource.class.getClassLoader().getResource(classPathLocation);
    if (resource == null) {
      resource = new URL("file://" + classPathLocation);
    }
    if (!"file".equals(resource.getProtocol())) {
      throw new IOException("Saving to property files inside a war, ear or jar is not possible.");
    }
    return new File(resource.toURI());
  }
}

代码示例来源:origin: ronmamo/reflections

public URL adaptURL(URL url) throws MalformedURLException {
  if (VFSZIP.equals(url.getProtocol())) {
    return replaceZipSeparators(url.getPath(), realFile);
  } else if (VFSFILE.equals(url.getProtocol())) {
    return new URL(url.toString().replace(VFSFILE, "file"));
  } else {
    return url;
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Extract the URL for the outermost archive from the given jar/war URL
 * (which may point to a resource in a jar file or to a jar file itself).
 * <p>In the case of a jar file nested within a war file, this will return
 * a URL to the war file since that is the one resolvable in the file system.
 * @param jarUrl the original URL
 * @return the URL for the actual jar file
 * @throws MalformedURLException if no valid jar file URL could be extracted
 * @since 4.1.8
 * @see #extractJarFileURL(URL)
 */
public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
  String urlFile = jarUrl.getFile();
  int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
  if (endIndex != -1) {
    // Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
    String warFile = urlFile.substring(0, endIndex);
    if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {
      return new URL(warFile);
    }
    int startIndex = warFile.indexOf(WAR_URL_PREFIX);
    if (startIndex != -1) {
      return new URL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));
    }
  }
  // Regular "jar:file:...myjar.jar!/myentry.txt"
  return extractJarFileURL(jarUrl);
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * If the first URL we try to access with a HTTP proxy is HTTPS then the authentication cache will not have been
 * pre-populated, so we try to access at least one HTTP URL before the very first HTTPS url.
 * @param proxy
 * @param url the actual URL being opened.
 */
private void jenkins48775workaround(Proxy proxy, URL url) {
  if ("https".equals(url.getProtocol()) && !authCacheSeeded && proxy != Proxy.NO_PROXY) {
    HttpURLConnection preAuth = null;
    try {
      // We do not care if there is anything at this URL, all we care is that it is using the proxy
      preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy);
      preAuth.setRequestMethod("HEAD");
      preAuth.connect();
    } catch (IOException e) {
      // ignore, this is just a probe we don't care at all
    } finally {
      if (preAuth != null) {
        preAuth.disconnect();
      }
    }
    authCacheSeeded = true;
  } else if ("https".equals(url.getProtocol())){
    // if we access any http url using a proxy then the auth cache will have been seeded
    authCacheSeeded = authCacheSeeded || proxy != Proxy.NO_PROXY;
  }
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

private void testExtractPathFromJarUrlNotDecodedIfFileExists(final String existingFile)
    throws MalformedURLException, UnsupportedEncodingException, URISyntaxException {
  URL url = ResolverUtilTest.class.getResource(existingFile);
  if (!url.getProtocol().equals("jar")) {
    // create fake jar: URL that resolves to existing file
    url = new URL("jar:" + url.toExternalForm() + "!/some/entry");
  }
  final String actual = new ResolverUtil().extractPath(url);
  assertTrue("should not be decoded: " + actual, actual.endsWith(existingFile));
}

代码示例来源:origin: prestodb/presto

/**
 * Helper methods used for constructing an optimal stream for
 * parsers to use, when input is to be read from an URL.
 * This helps when reading file content via URL.
 */
protected InputStream _optimizedStreamFromURL(URL url) throws IOException {
  if ("file".equals(url.getProtocol())) {
    /* Can not do this if the path refers
     * to a network drive on windows. This fixes the problem;
     * might not be needed on all platforms (NFS?), but should not
     * matter a lot: performance penalty of extra wrapping is more
     * relevant when accessing local file system.
     */
    String host = url.getHost();
    if (host == null || host.length() == 0) {
      // [core#48]: Let's try to avoid probs with URL encoded stuff
      String path = url.getPath();
      if (path.indexOf('%') < 0) {
        return new FileInputStream(url.getPath());
      }
      // otherwise, let's fall through and let URL decoder do its magic
    }
  }
  return url.openStream();
}

代码示例来源:origin: apache/incubator-druid

private String getPoolKey(URL url)
 {
  return StringUtils.format(
    "%s://%s:%s", url.getProtocol(), url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort()
  );
 }
}

代码示例来源:origin: stackoverflow.com

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

代码示例来源:origin: spring-projects/spring-framework

/**
 * Resolve the given resource URL to a {@code java.io.File},
 * i.e. to a file in the file system.
 * @param resourceUrl the resource URL to resolve
 * @param description a description of the original resource that
 * the URL was created for (for example, a class path location)
 * @return a corresponding File object
 * @throws FileNotFoundException if the URL cannot be resolved to
 * a file in the file system
 */
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
  Assert.notNull(resourceUrl, "Resource URL must not be null");
  if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
    throw new FileNotFoundException(
        description + " cannot be resolved to absolute file path " +
        "because it does not reside in the file system: " + resourceUrl);
  }
  try {
    return new File(toURI(resourceUrl).getSchemeSpecificPart());
  }
  catch (URISyntaxException ex) {
    // Fallback for URLs that are not valid URIs (should hardly ever happen).
    return new File(resourceUrl.getFile());
  }
}

代码示例来源:origin: google/j2objc

@VisibleForTesting
 static File toFile(URL url) {
  checkArgument(url.getProtocol().equals("file"));
  try {
   return new File(url.toURI()); // Accepts escaped characters like %20.
  } catch (URISyntaxException e) { // URL.toURI() doesn't escape chars.
   return new File(url.getPath()); // Accepts non-escaped chars like space.
  }
 }
}

代码示例来源:origin: jenkinsci/jenkins

while (st.hasMoreTokens()) {
  String classpathElement = st.nextToken();
  URL libraryURL = new URL(baseURL, classpathElement);
  if (!libraryURL.getProtocol().equals("file")) {
    log("Skipping jar library " + classpathElement
        + " since only relative URLs are supported by this" + " loader",
    continue;
  String decodedPath = Locator.decodeUri(libraryURL.getFile());
  File libraryFile = new File(decodedPath);
  if (libraryFile.exists() && !isInPath(libraryFile)) {
    addPathFile(libraryFile);

代码示例来源:origin: org.springframework.boot/spring-boot

private Resource createResource(URL url) throws Exception {
  if ("file".equals(url.getProtocol())) {
    File file = new File(url.toURI());
    if (file.isFile()) {
      return Resource.newResource("jar:" + url + "!/META-INF/resources");
    }
  }
  return Resource.newResource(url + "META-INF/resources");
}

代码示例来源:origin: org.reflections/reflections

public URL adaptURL(URL url) throws MalformedURLException {
  if (VFSZIP.equals(url.getProtocol())) {
    return replaceZipSeparators(url.getPath(), realFile);
  } else if (VFSFILE.equals(url.getProtocol())) {
    return new URL(url.toString().replace(VFSFILE, "file"));
  } else {
    return url;
  }
}

代码示例来源:origin: org.springframework/spring-core

/**
 * Extract the URL for the outermost archive from the given jar/war URL
 * (which may point to a resource in a jar file or to a jar file itself).
 * <p>In the case of a jar file nested within a war file, this will return
 * a URL to the war file since that is the one resolvable in the file system.
 * @param jarUrl the original URL
 * @return the URL for the actual jar file
 * @throws MalformedURLException if no valid jar file URL could be extracted
 * @since 4.1.8
 * @see #extractJarFileURL(URL)
 */
public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
  String urlFile = jarUrl.getFile();
  int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
  if (endIndex != -1) {
    // Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
    String warFile = urlFile.substring(0, endIndex);
    if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {
      return new URL(warFile);
    }
    int startIndex = warFile.indexOf(WAR_URL_PREFIX);
    if (startIndex != -1) {
      return new URL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));
    }
  }
  // Regular "jar:file:...myjar.jar!/myentry.txt"
  return extractJarFileURL(jarUrl);
}

相关文章