List of usage examples for java.net JarURLConnection getJarFile
public abstract JarFile getJarFile() throws IOException;
From source file:net.dataforte.commons.resources.ClassUtils.java
/** * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS * //from w ww . ja va2s .c o m * @param folder * @return * @throws IOException */ public static URL[] getResources(String folder) throws IOException { List<URL> urls = new ArrayList<URL>(); ArrayList<File> directories = new ArrayList<File>(); try { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new IOException("Can't get class loader."); } // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(folder); while (resources.hasMoreElements()) { URL res = resources.nextElement(); String resProtocol = res.getProtocol(); if (resProtocol.equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) res.openConnection(); JarFile jar = conn.getJarFile(); for (JarEntry e : Collections.list(jar.entries())) { if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) { urls.add(new URL( joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name } } } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+ try { Object content = res.getContent(); Method getChildren = content.getClass().getMethod("getChildren"); List<?> files = (List<?>) getChildren.invoke(res.getContent()); Method toUrl = null; for (Object o : files) { if (toUrl == null) { toUrl = o.getClass().getMethod("toURL"); } urls.add((URL) toUrl.invoke(o)); } } catch (Exception e) { throw new IOException("Error while scanning " + res.toString(), e); } } else if (resProtocol.equalsIgnoreCase("file")) { directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } else { throw new IOException("Unknown protocol for resource: " + res.toString()); } } } catch (NullPointerException x) { throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)"); } // For every directory identified capture all the .class files for (File directory : directories) { if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file))); } } else { throw new IOException( folder + " (" + directory.getPath() + ") does not appear to be a valid folder"); } } URL[] urlsA = new URL[urls.size()]; urls.toArray(urlsA); return urlsA; }
From source file:net.dataforte.commons.resources.ClassUtils.java
/** * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS * /*from ww w . j a va 2s. co m*/ * @param folder * @return * @throws IOException */ public static Class<?>[] getClassesForPackage(String pckgname) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. // There may be more than one if a package is split over multiple // jars/paths List<Class<?>> classes = new ArrayList<Class<?>>(); ArrayList<File> directories = new ArrayList<File>(); try { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/')); while (resources.hasMoreElements()) { URL res = resources.nextElement(); if (res.getProtocol().equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) res.openConnection(); JarFile jar = conn.getJarFile(); for (JarEntry e : Collections.list(jar.entries())) { if (e.getName().startsWith(pckgname.replace('.', '/')) && e.getName().endsWith(".class") && !e.getName().contains("$")) { String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6); classes.add(Class.forName(className, true, cld)); } } } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+ try { Object content = res.getContent(); Method getChildren = content.getClass().getMethod("getChildren"); List<?> files = (List<?>) getChildren.invoke(res.getContent()); Method getPathName = null; for (Object o : files) { if (getPathName == null) { getPathName = o.getClass().getMethod("getPathName"); } String pathName = (String) getPathName.invoke(o); if (pathName.endsWith(".class")) { String className = pathName.replace("/", ".").substring(0, pathName.length() - 6); classes.add(Class.forName(className, true, cld)); } } } catch (Exception e) { throw new IOException("Error while scanning " + res.toString(), e); } } else { directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } } } catch (NullPointerException x) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)", x); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)", encex); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname, ioex); } // For every directory identified capture all the .class files for (File directory : directories) { if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6))); } } } else { throw new ClassNotFoundException( pckgname + " (" + directory.getPath() + ") does not appear to be a valid package"); } } Class<?>[] classesA = new Class[classes.size()]; classes.toArray(classesA); return classesA; }
From source file:eu.sisob.uma.footils.File.FileFootils.java
public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection) throws IOException { final JarFile jarFile = jarConnection.getJarFile(); for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { final JarEntry entry = e.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { final String filename = StringUtils.removeStart(entry.getName(), // jarConnection.getEntryName()); final File f = new File(destDir, filename); if (!entry.isDirectory()) { final InputStream entryInputStream = jarFile.getInputStream(entry); if (!FileFootils.copyStream(entryInputStream, f)) { return false; }/*w w w. j av a 2 s . c om*/ entryInputStream.close(); } else { if (!FileFootils.ensureDirectoryExists(f)) { throw new IOException("Could not create directory: " + f.getAbsolutePath()); } } } } return true; }
From source file:io.tempra.AppServer.java
public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) { try {//from w w w . java 2s . c o m JarFile jarFile = jarConnection.getJarFile(); /** * Iterate all entries in the jar file. */ for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { JarEntry jarEntry = e.nextElement(); String jarEntryName = jarEntry.getName(); String jarConnectionEntryName = jarConnection.getEntryName(); /** * Extract files only if they match the path. */ if (jarEntryName.startsWith(jarConnectionEntryName)) { String filename = jarEntryName.startsWith(jarConnectionEntryName) ? jarEntryName.substring(jarConnectionEntryName.length()) : jarEntryName; File currentFile = new File(destDir, filename); if (jarEntry.isDirectory()) { currentFile.mkdirs(); } else { InputStream is = jarFile.getInputStream(jarEntry); OutputStream out = FileUtils.openOutputStream(currentFile); IOUtils.copy(is, out); is.close(); out.close(); } } } } catch (IOException e) { // TODO add logger e.printStackTrace(); } }
From source file:com.github.sakserv.minicluster.impl.KnoxLocalCluster.java
public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection) throws IOException { final JarFile jarFile = jarConnection.getJarFile(); for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { final JarEntry entry = e.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { final String filename = StringUtils.removeStart(entry.getName(), // jarConnection.getEntryName()); final File f = new File(destDir, filename); if (!entry.isDirectory()) { final InputStream entryInputStream = jarFile.getInputStream(entry); if (!copyStream(entryInputStream, f)) { return false; }//w w w. ja va2 s.c om entryInputStream.close(); } else { if (!ensureDirectoryExists(f)) { throw new IOException("Could not create directory: " + f.getAbsolutePath()); } } } } return true; }
From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java
/** * Copies a directory from a {@link JarURLConnection} to a destination * Directory outside the jar./*from w ww . j a v a 2 s . c om*/ * * @param destDir * @param jarConnection * @return true if copy is successful, false otherwise. * @throws IOException */ public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection) throws IOException { logger.debug("copyJarResourcesRecursively()"); boolean success = true; final JarFile jarFile = jarConnection.getJarFile(); for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { final JarEntry entry = e.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { final String filename = StringUtils.removeStart(entry.getName(), // jarConnection.getEntryName()); final File f = new File(destDir, filename); if (!entry.isDirectory()) { final InputStream entryInputStream = jarFile.getInputStream(entry); if (!FileInstaller.copyStream(entryInputStream, f)) { success = false; logger.debug("returning " + success); return success; } entryInputStream.close(); } else { if (!FileInstaller.ensureDirectoryExists(f)) { logger.debug("throwing an IOException"); throw new IOException("Could not create directory: " + f.getAbsolutePath()); } } } } logger.debug("returning " + success); return success; }
From source file:JarUtils.java
/** Given a URL check if its a jar url(jar:<url>!/archive) and if it is, extract the archive entry into the given dest directory and return a file URL to its location. If jarURL is not a jar url then it is simply returned as the URL for the jar.// w ww . j av a 2 s . com @param jarURL the URL to validate and extract the referenced entry if its a jar protocol URL @param dest the directory into which the nested jar will be extracted. @return the file: URL for the jar referenced by the jarURL parameter. * @throws IOException */ public static URL extractNestedJar(URL jarURL, File dest) throws IOException { // This may not be a jar URL so validate the protocol if (jarURL.getProtocol().equals("jar") == false) return jarURL; String destPath = dest.getAbsolutePath(); URLConnection urlConn = jarURL.openConnection(); JarURLConnection jarConn = (JarURLConnection) urlConn; // Extract the archive to dest/jarName-contents/archive String parentArchiveName = jarConn.getJarFile().getName(); // Find the longest common prefix between destPath and parentArchiveName int length = Math.min(destPath.length(), parentArchiveName.length()); int n = 0; while (n < length) { char a = destPath.charAt(n); char b = parentArchiveName.charAt(n); if (a != b) break; n++; } // Remove any common prefix from parentArchiveName parentArchiveName = parentArchiveName.substring(n); File archiveDir = new File(dest, parentArchiveName + "-contents"); if (archiveDir.exists() == false && archiveDir.mkdirs() == false) throw new IOException( "Failed to create contents directory for archive, path=" + archiveDir.getAbsolutePath()); String archiveName = jarConn.getEntryName(); File archiveFile = new File(archiveDir, archiveName); File archiveParentDir = archiveFile.getParentFile(); if (archiveParentDir.exists() == false && archiveParentDir.mkdirs() == false) throw new IOException( "Failed to create parent directory for archive, path=" + archiveParentDir.getAbsolutePath()); InputStream archiveIS = jarConn.getInputStream(); FileOutputStream fos = new FileOutputStream(archiveFile); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[4096]; int read; while ((read = archiveIS.read(buffer)) > 0) { bos.write(buffer, 0, read); } archiveIS.close(); bos.close(); // Return the file url to the extracted jar return archiveFile.toURL(); }
From source file:org.apache.wiki.util.ClassUtil.java
/** * Searchs for all the files in classpath under a given package, for a given {@link JarURLConnection}. * /*ww w . j a v a2 s .c o m*/ * @param results collection in which the found entries are stored * @param jurlcon given {@link JarURLConnection} to search in. * @param rootPackage base package. */ static void jarEntriesUnder(List<String> results, JarURLConnection jurlcon, String rootPackage) { JarFile jar = null; try { jar = jurlcon.getJarFile(); log.debug("scanning [" + jar.getName() + "]"); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(rootPackage) && !entry.isDirectory()) { results.add(entry.getName()); } } } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); } finally { if (jar != null) { try { jar.close(); } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); } } } }
From source file:org.dacapo.harness.CommandLineArgs.java
static List<String> extractBenchmarkSet() throws IOException { List<String> benchmarks = new ArrayList<String>(); URL url = CommandLineArgs.class.getClassLoader().getResource("cnf"); String protocol = url.getProtocol(); if (protocol.equals("jar")) { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); for (Enumeration<?> entries = jarConnection.getJarFile().entries(); entries.hasMoreElements();) { String entry = ((JarEntry) entries.nextElement()).getName(); if (entry.endsWith(".cnf")) { entry = entry.replace("cnf/", "").replace(".cnf", ""); benchmarks.add(entry);/*from w ww . jav a 2 s. c o m*/ } } } else if (protocol.equals("file")) { File dir = new File(url.getFile()); if (dir.isDirectory()) { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { String entry = files[i].toString(); entry = entry.substring(entry.lastIndexOf('/') + 1, entry.length()); entry = entry.replace(".cnf", ""); benchmarks.add(entry); } } } return benchmarks; }
From source file:net.kamhon.ieagle.util.ReflectionUtil.java
/** * <pre>/*from w ww. j a v a 2 s . c om*/ * 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; }