List of usage examples for java.net URL getFile
public String getFile()
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
/** * Get a list of resources from class path directory. Attention: path must * be a path !//from w ww. j a v a2 s. c o m * * @param path * @return * @throws IOException * @throws de.unibi.techfak.bibiserv.util.codegen.CodeGenParserException */ public static List<String> getClasspathEntriesByPath(String path) throws IOException, CodeGenParserException { try { List<String> tmp = new ArrayList<>(); URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation(); String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8"); JarFile jarFile = new JarFile(jarPath); String prefix = path.startsWith("/") ? path.substring(1) : path; Enumeration<JarEntry> enu = jarFile.entries(); while (enu.hasMoreElements()) { JarEntry je = enu.nextElement(); if (!je.isDirectory()) { String name = je.getName(); if (name.startsWith(prefix)) { tmp.add("/" + name); } } } return tmp; } catch (Exception e) { // maybe we start Main.class not from Jar. } InputStream is = Main.class.getResourceAsStream(path); if (is == null) { throw new CodeGenParserException("Path '" + path + "' not found in Classpath!"); } StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024]; while (is.read(buffer) != -1) { sb.append(new String(buffer, Charset.defaultCharset())); } is.close(); return Arrays.asList(sb.toString().split("\n")) // Convert StringBuilder to individual lines .stream() // Stream the list .filter(line -> line.trim().length() > 0) // Filter out empty lines .map(line -> path + "/" + line) // add path for each entry .collect(Collectors.toList()); // Collect remaining lines into a List again }
From source file:org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase.java
/** * Returns a new FileSystem to read REST resources, or null if they * are available from classpath.//from w w w .ja v a 2 s . c om */ @SuppressForbidden(reason = "proper use of URL, hack around a JDK bug") protected static FileSystem getFileSystem() throws IOException { // REST suite handling is currently complicated, with lots of filtering and so on // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents. URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation(); boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true); if (codeLocation.getFile().endsWith(".jar") && loadPackaged) { try { // hack around a bug in the zipfilesystem implementation before java 9, // its checkWritable was incorrect and it won't work without write permissions. // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location. Path tmp = Files.createTempFile(null, ".jar"); try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) { Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING); } return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap()); } catch (URISyntaxException e) { throw new IOException("couldn't open zipfilesystem: ", e); } } else { return null; } }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
public static File getFile(URL url) throws IOException { if (url == null) { return null; }/*from w w w. ja v a 2 s . c om*/ if (PROTOCOL_FILE.equals(url.getProtocol()) || PROTOCOL_PLATFORM.equalsIgnoreCase(url.getProtocol())) { File file; try { file = new File(new URI(url.toExternalForm())); } catch (Exception e) { file = new File(url.getFile()); } if (!file.exists()) { return null; } return file; } File file = getCachedFile(url); long urlLastModified = getLastModified(url); if (file.exists()) { long lastModified = file.lastModified(); if (urlLastModified > lastModified) { file = download(file, url); if (file != null) { file.setLastModified(urlLastModified); } } } else { file = download(file, url); if (file != null && urlLastModified > -1) { file.setLastModified(urlLastModified); } } return file; }
From source file:podd.util.PoddWebappTestUtil.java
public static String getAdminProperty(String key) throws IOException { Properties adminProperties = new Properties(); final URL url = getClassLoader().getResource("test.admin.properties"); FileInputStream in = new FileInputStream(new File(url.getFile())); adminProperties.load(in);/*from w ww . j a v a 2 s . co m*/ in.close(); return adminProperties.get(key).toString(); }
From source file:net.kamhon.ieagle.util.ReflectionUtil.java
/** * <pre>//from w w w.j av a 2 s . c o m * This method finds all classes that are located in the package identified by * the given * <code> * packageName * </code> * . * <br> * <b>ATTENTION:</b> * <br> * This is a relative expensive operation. Depending on your classpath * multiple directories,JAR, and WAR files may need to scanned. * * @param packageName is the name of the {@link Package} to scan. * @param includeSubPackages - if * <code> * true * </code> * all sub-packages of the * specified {@link Package} will be included in the search. * @return a {@link Set} will the fully qualified names of all requested * classes. * @throws IOException if the operation failed with an I/O error. * @see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java * </pre> */ public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern, String... endWiths) throws IOException { Set<String> classSet = new HashSet<String>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String path = packageName.replace('.', '/'); String pathWithPrefix = path + '/'; Enumeration<URL> urls = classLoader.getResources(path); StringBuilder qualifiedNameBuilder = new StringBuilder(packageName); qualifiedNameBuilder.append('.'); int qualifiedNamePrefixLength = qualifiedNameBuilder.length(); while (urls.hasMoreElements()) { URL packageUrl = urls.nextElement(); String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8"); String protocol = packageUrl.getProtocol().toLowerCase(); log.debug(urlString); if ("file".equals(protocol)) { File packageDirectory = new File(urlString); if (packageDirectory.isDirectory()) { if (includeSubPackages) { findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder, qualifiedNamePrefixLength, packagePattern); } else { for (String fileName : packageDirectory.list()) { String simpleClassName = fixClassName(fileName); if (simpleClassName != null) { qualifiedNameBuilder.setLength(qualifiedNamePrefixLength); qualifiedNameBuilder.append(simpleClassName); if (qualifiedNameBuilder.toString().matches(packagePattern)) classSet.add(qualifiedNameBuilder.toString()); } } } } } else if ("jar".equals(protocol)) { // somehow the connection has no close method and can NOT be // disposed JarURLConnection connection = (JarURLConnection) packageUrl.openConnection(); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); while (jarEntryEnumeration.hasMoreElements()) { JarEntry jarEntry = jarEntryEnumeration.nextElement(); String absoluteFileName = jarEntry.getName(); // if (absoluteFileName.endsWith(".class")) { //original if (endWith(absoluteFileName, endWiths)) { // modified if (absoluteFileName.startsWith("/")) { absoluteFileName.substring(1); } // special treatment for WAR files... // "WEB-INF/lib/" entries should be opened directly in // contained jar if (absoluteFileName.startsWith("WEB-INF/classes/")) { // "WEB-INF/classes/".length() == 16 absoluteFileName = absoluteFileName.substring(16); } boolean accept = true; if (absoluteFileName.startsWith(pathWithPrefix)) { String qualifiedName = absoluteFileName.replace('/', '.'); if (!includeSubPackages) { int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1); if (index != -1) { accept = false; } } if (accept) { String className = fixClassName(qualifiedName); if (className != null) { if (qualifiedNameBuilder.toString().matches(packagePattern)) classSet.add(className); } } } } } } else { log.debug("unknown protocol -> " + protocol); } } return classSet; }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
public static List<String> getAllClasses(ClassLoader cl, String packageName) { packageName = packageName.replace('.', '/'); List<String> classes = new ArrayList<>(); URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { //System.out.println(url.getFile()); File jar = new File(url.getFile()); if (jar.isDirectory()) { File subdir = new File(jar, packageName); if (!subdir.exists()) continue; File[] files = subdir.listFiles(); for (File file : files) { if (!file.isFile()) continue; if (file.getName().endsWith(".class")) classes.add(file.getName().substring(0, file.getName().length() - 6).replace('/', '.')); }//from ww w . j a va2s .com } else { // try to open as ZIP try { ZipFile zip = new ZipFile(jar); for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (!name.startsWith(packageName)) continue; if (name.endsWith(".class") && name.indexOf('$') < 0) classes.add(name.substring(0, name.length() - 6).replace('/', '.')); } zip.close(); } catch (ZipException e) { //System.out.println("Not a ZIP: " + e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } } } return classes; }
From source file:ChartThemesApp.java
/** * @param fileName// w ww.ja va 2 s .c o m * to be found on a class path. * @return file found on class path. */ public final static File findFile(String fileName) { Assert.hasLength(fileName); URL url = ChartThemesApp.class.getResource(fileName); Assert.notNull(url); return new File(url.getFile()); }
From source file:edu.internet2.middleware.psp.util.PSPUtil.java
public static File getFile(String resourceName) { URL url = PSPUtil.class.getClassLoader().getResource(resourceName); if (url == null) { return null; }//from www . ja v a 2 s . co m File file = new File(url.getFile()); if (!file.exists()) { return null; } return file; }
From source file:UrlHelper.java
public static void downloadFile(String adresse, File dest) { BufferedReader reader = null; FileOutputStream fos = null;/*from ww w.j a v a 2 s .c o m*/ InputStream in = null; try { // cration de la connection URL url = new URL(adresse); URLConnection conn = url.openConnection(); String FileType = conn.getContentType(); int FileLenght = conn.getContentLength(); if (FileLenght == -1) { throw new IOException("Fichier non valide."); } // lecture de la rponse in = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); if (dest == null) { String FileName = url.getFile(); FileName = FileName.substring(FileName.lastIndexOf('/') + 1); dest = new File(FileName); } fos = new FileOutputStream(dest); byte[] buff = new byte[1024]; int l = in.read(buff); while (l > 0) { fos.write(buff, 0, l); l = in.read(buff); } } catch (Exception e) { e.printStackTrace(); } finally { try { fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java
public static byte[] createSignedAndZippedPkPassArchive(final PKPass pass, final URL fileUrlOfTemplateDirectory, final PKSigningInformation signingInformation) throws Exception { String pathToTemplateDirectory = URLDecoder.decode(fileUrlOfTemplateDirectory.getFile(), "UTF-8"); return createSignedAndZippedPkPassArchive(pass, pathToTemplateDirectory, signingInformation); }