/** * Returns a {@link File} named {@code fileName} associated with {@link Class} {@code resourceClass} . * * @param resourceClass The associated class * @param fileName The file name * @return The file named {@code fileName} associated with {@link Class} {@code resourceClass} . */ public static File getFile(Class resourceClass, String fileName) { try { return new File(URLDecoder.decode(resourceClass.getResource(fileName).getFile(), "UTF-8")); } catch (UnsupportedEncodingException e) { return new File(resourceClass.getResource(fileName).getFile()); } }
/** * Extract the URL for the actual jar file from the given URL * (which may point to a resource in a jar file or to a jar file itself). * @param jarUrl the original URL * @return the URL for the actual jar file * @throws MalformedURLException if no valid jar file URL could be extracted */ public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException { String urlFile = jarUrl.getFile(); int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); if (separatorIndex != -1) { String jarFile = urlFile.substring(0, separatorIndex); try { return new URL(jarFile); } catch (MalformedURLException ex) { // Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar". // This usually indicates that the jar file resides in the file system. if (!jarFile.startsWith("/")) { jarFile = "/" + jarFile; } return new URL(FILE_URL_PREFIX + jarFile); } } else { return jarUrl; } }
@Override public boolean apply(@Nullable URL input) { return input != null && (!input.getProtocol().equals("file") || new File(input.getFile()).exists()); } }));
protected long getLastModifiedDate(String fileName) { URL resource = Thread.currentThread().getContextClassLoader().getResource(fileName); // Get the absolute path. String filePath = (resource == null) ? fileName : URLDecoder.decode(resource.getFile()); ; // If the jobs file is inside a jar point to the jar file (to get it modification date). // Otherwise continue as usual. int jarIndicator = filePath.indexOf('!'); if (jarIndicator > 0) { filePath = filePath.substring(5, filePath.indexOf('!')); } File file = new File(filePath); if(!file.exists()) { return -1; } else { return file.lastModified(); } } }
/** * Appends a trailing '/' to a {@link URL} object. Does not append a slash if one is already present. * * @param originalURL The URL to append a slash to * @return a new URL object that ends in a slash */ public static URL appendTrailingSlash(URL originalURL) { try { return originalURL.getPath().endsWith("/") ? originalURL : new URL(originalURL.getProtocol(), originalURL.getHost(), originalURL.getPort(), originalURL.getFile() + '/'); } catch (MalformedURLException ignored) { // shouldn't happen throw new IllegalArgumentException("Invalid resource URL: " + originalURL); } }
private void generate() throws Exception { File current = new File(templateFile); if (current.exists()) { ClassLoader loader = GenHiveTemplate.class.getClassLoader(); URL url = loader.getResource("org/apache/hadoop/hive/conf/HiveConf.class"); if (url != null) { File file = new File(url.getFile()); if (file.exists() && file.lastModified() < current.lastModified()) { return; } } } writeToFile(current, generateTemplate()); }
protected void processIsInJarAndlastModified() { if ("file".equalsIgnoreCase(url.getProtocol())) { isInJar = false; lastModified = new File(url.getFile()).lastModified(); } else { isInJar = true; lastModified = -1; } }
/** * 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()); } }
url = new URL(systemId); _tohFactory.setOutputStream( _ostream = new FileOutputStream(url.getFile())); return _tohFactory.getSerializationHandler(); url = new URL(systemId); final URLConnection connection = url.openConnection(); _tohFactory.setOutputStream(_ostream = connection.getOutputStream()); url = new File(systemId).toURL(); _tohFactory.setOutputStream( _ostream = new FileOutputStream(url.getFile())); return _tohFactory.getSerializationHandler();
/** * 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); }
@Override public HttpClientRequest requestAbs(HttpMethod method, String absoluteURI) { URL url = parseUrl(absoluteURI); Boolean ssl = false; int port = url.getPort(); String relativeUri = url.getPath().isEmpty() ? "/" + url.getFile() : url.getFile(); String protocol = url.getProtocol(); if ("ftp".equals(protocol)) { if (port == -1) { port = 21; } } else { char chend = protocol.charAt(protocol.length() - 1); if (chend == 'p') { if (port == -1) { port = 80; } } else if (chend == 's'){ ssl = true; if (port == -1) { port = 443; } } } // if we do not know the protocol, the port still may be -1, we will handle that below return createRequest(method, protocol, url.getHost(), port, ssl, relativeUri, null); }
/** * Converts file URLs to file name. Accepts only URLs with 'file' protocol. * Otherwise, for other schemes returns <code>null</code>. */ public static String toFileName(URL url) { if ((url == null) || !(url.getProtocol().equals("file"))) { return null; } String filename = url.getFile().replace('/', File.separatorChar); return URLDecoder.decode(filename, JoddCore.encoding); }
static URL tryToGetValidUrl(String workingDir, String path, String filename) { try { if (new File(filename).exists()) return new File(filename).toURI().toURL(); if (new File(path + File.separator + filename).exists()) return new File(path + File.separator + filename).toURI().toURL(); if (new File(workingDir + File.separator + filename).exists()) return new File(workingDir + File.separator + filename).toURI().toURL(); if (new File(new URL(filename).getFile()).exists()) return new File(new URL(filename).getFile()).toURI().toURL(); } catch (MalformedURLException e) { // don't do anything, we're going on the assumption it is a jar, which could be wrong } return null; }
while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); if (!directory.exists()) { return classes; for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
private static URL getParentURL(URL url) throws IOException { URL fileURL = ((JarURLConnection) url.openConnection()).getJarFileURL(); String file = fileURL.getFile(); String parentFile = new File(file).getParent(); parentFile = parentFile.replace(File.separatorChar, '/'); if (parentFile.charAt(0) != '/') { parentFile = "/" + parentFile; } URL parentURL = new URL(fileURL.getProtocol(), fileURL .getHost(), fileURL.getPort(), parentFile); return parentURL; }
/** * Returns the jar file from which the given class is loaded; or null * if no such jar file can be located. */ public static JarFile jarFileOf(Class<?> klass) { URL url = klass.getResource( "/" + klass.getName().replace('.', '/') + ".class"); if (url == null) return null; String s = url.getFile(); int beginIndex = s.indexOf("file:") + "file:".length(); int endIndex = s.indexOf(".jar!"); if (endIndex == -1) return null; endIndex += ".jar".length(); String f = s.substring(beginIndex, endIndex); File file = new File(f); try { return file.exists() ? new JarFile(file) : null; } catch (IOException e) { throw new IllegalStateException(e); } } }
/** * 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()); } }