List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:com.eviware.soapui.plugins.JarClassLoader.java
private void addLibrariesIn(JarFile jarFile) throws IOException { if (containsLibraries(jarFile)) { File libDirectory = Tools.createTemporaryDirectory(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (isLibrary(jarEntry)) { String fileName = jarEntry.getName().substring(LIB_PREFIX.length()); File outputFile = new File(libDirectory, fileName); FileUtils.copyInputStreamToFile(jarFile.getInputStream(jarEntry), outputFile); this.addURL(outputFile.toURI().toURL()); }/* w ww . j a v a 2 s . c o m*/ } } }
From source file:org.mule.util.scan.ClasspathScanner.java
protected <T> Set<Class<T>> processJarUrl(URL url, String basepath, Class<T> clazz, int flags) throws IOException { Set<Class<T>> set = new HashSet<Class<T>>(); String path = url.getFile().substring(5, url.getFile().indexOf("!")); // We can't URLDecoder.decode(path) since some encoded chars are allowed on file uris path = path.replaceAll("%20", " "); JarFile jar = new JarFile(path); for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) { try { String name = entry.getName(); // Ignore anonymous and inner classes if (name.contains("$") && !hasFlag(flags, INCLUDE_INNER)) { continue; }//from ww w . ja v a2s. c om URL classURL = classLoader.getResource(name); InputStream classStream = classURL.openStream(); ClassReader reader = new ClosableClassReader(classStream); ClassScanner visitor = getScanner(clazz); reader.accept(visitor, 0); if (visitor.isMatch()) { @SuppressWarnings("unchecked") Class<T> loadedClass = (Class<T>) loadClass(visitor.getClassName()); addClassToSet(loadedClass, set, flags); } } catch (Exception e) { if (logger.isDebugEnabled()) { Throwable t = ExceptionHelper.getRootException(e); logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString())); } } } } jar.close(); return set; }
From source file:org.jdesktop.wonderland.modules.service.PendingManager.java
/** * Takes a base directory (which must exist and be readable) and expands * the contents of the archive module into that directory given the * URL of the module encoded as a jar file * /*from www .j a va 2 s .c o m*/ * @param root The base directory in which the module is expanded * @throw IOException Upon error */ private void expand(File root, File jar) throws IOException { /* * Loop through each entry, fetch its input stream, and write to an * output stream for the file. */ JarFile jarFile = new JarFile(jar); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements() == true) { /* Fetch the next entry, its name is the relative file name */ JarEntry entry = entries.nextElement(); String entryName = entry.getName(); long size = entry.getSize(); /* Don't expand anything that beings with META-INF */ if (entryName.startsWith("META-INF") == true) { continue; } /* Ignore if it is a directory, then create it */ if (entryName.endsWith("/") == true) { File file = new File(root, entryName); file.mkdirs(); continue; } /* Write out to a file in 'root' */ File file = new File(root, entryName); InputStream jis = jarFile.getInputStream(entry); FileOutputStream os = new FileOutputStream(file); byte[] b = new byte[PendingManager.CHUNK_SIZE]; long read = 0; while (read < size) { int len = jis.read(b); if (len == -1) { break; } read += len; os.write(b, 0, len); } jis.close(); os.close(); } }
From source file:org.mksmart.ecapi.couchdb.CouchDbSanityChecker.java
/** * Utility method, might need to move elsewhere. * /*from w w w . ja v a 2 s. co m*/ * @param path * @return * @throws URISyntaxException * @throws IOException */ protected String[] listSubResources(String path) throws URISyntaxException, IOException { URL dirURL = getClass().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { // A file path: easy enough return new File(dirURL.toURI()).list(); } // In case of a jar file, we can't actually find a directory. // Have to assume the same jar as this class. if (dirURL == null) { String me = getClass().getName().replace(".", "/") + ".class"; dirURL = getClass().getClassLoader().getResource(me); } // a JAR path if (dirURL.getProtocol().equals("jar")) { // strip out only the JAR file String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar Set<String> result = new HashSet<String>(); // avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { // filter according to the path String entry = name.substring(path.length()); if (entry.startsWith("/")) entry = entry.substring(1); int checkSubdir = entry.indexOf("/"); // if it is a subdirectory, we just return the directory name if (checkSubdir >= 0) entry = entry.substring(0, checkSubdir); if (!entry.isEmpty()) result.add(entry); } } jar.close(); return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java
/** * Scan a classloader for classes under the given package. * @param pkg package name//www. j a v a 2 s.c o m * @param loader classloader * @param lookInsideJars whether to consider classes inside jars or only "unpacked" class files * @return matching class names (will not attemp to actually load these classes) */ private Collection<String> scanClasspath(String pkg, ClassLoader loader, boolean lookInsideJars) { Collection<String> classes = Lists.newArrayList(); Enumeration<URL> resources; String packageDir = pkg.replace(PACKAGE_SEPARATOR, JAR_PATH_SEPARATOR) + JAR_PATH_SEPARATOR; try { resources = loader.getResources(packageDir); } catch (IOException e) { s_log.warn("couldn't scan package", e); return classes; } while (resources.hasMoreElements()) { URL resource = resources.nextElement(); String path = resource.getPath(); s_log.debug("processing path {}", path); if (path.startsWith(FILE_URL_PREFIX)) { if (lookInsideJars) { String jarFilePath = StringUtils.substringBetween(path, FILE_URL_PREFIX, NESTED_FILE_URL_SEPARATOR); try { JarFile jarFile = new JarFile(jarFilePath); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { String entryName = entries.nextElement().getName(); if (entryName.startsWith(packageDir) && entryName.endsWith(CLASS_NAME_SUFFIX)) { String potentialClassName = entryName.substring(packageDir.length(), entryName.length() - CLASS_NAME_SUFFIX.length()); if (!potentialClassName.contains(JAR_PATH_SEPARATOR)) { classes.add(pkg + PACKAGE_SEPARATOR + potentialClassName); } } } } catch (IOException e) { s_log.warn("couldn't open jar file", e); } } } else { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { String[] files = dir.list(); for (String file : files) { s_log.debug("file {}", file); if (file.endsWith(CLASS_NAME_SUFFIX)) { classes.add(pkg + PACKAGE_SEPARATOR + StringUtils.removeEnd(file, CLASS_NAME_SUFFIX)); } } } } } return classes; }
From source file:org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter.java
private String getGroupIdFromPackage(File artifactFile) { try {//from w w w . j a v a2s.c o m /* get package names from jar */ Set packageNames = new HashSet(); JarFile jar = new JarFile(artifactFile, false); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().endsWith(".class")) { File f = new File(entry.getName()); String packageName = f.getParent(); if (packageName != null) { packageNames.add(packageName); } } } jar.close(); /* find the top package */ String[] groupIdSections = null; for (Iterator it = packageNames.iterator(); it.hasNext();) { String packageName = (String) it.next(); String[] packageNameSections = packageName.split("\\" + FILE_SEPARATOR); if (groupIdSections == null) { /* first candidate */ groupIdSections = packageNameSections; } else // if ( packageNameSections.length < groupIdSections.length ) { /* * find the common portion of current package and previous selected groupId */ int i; for (i = 0; (i < packageNameSections.length) && (i < groupIdSections.length); i++) { if (!packageNameSections[i].equals(groupIdSections[i])) { break; } } groupIdSections = new String[i]; System.arraycopy(packageNameSections, 0, groupIdSections, 0, i); } } if ((groupIdSections == null) || (groupIdSections.length == 0)) { return null; } /* only one section as id doesn't seem enough, so ignore it */ if (groupIdSections.length == 1) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < groupIdSections.length; i++) { sb.append(groupIdSections[i]); if (i < groupIdSections.length - 1) { sb.append('.'); } } return sb.toString(); } catch (IOException e) { /* we took all the precautions to avoid this */ throw new RuntimeException(e); } }
From source file:org.kitodo.serviceloader.KitodoServiceLoader.java
/** * Checks, whether a passed jarFile has frontend files or not. Returns true, * when the jar contains a folder with the name "resources" * * @param jarFile//from w w w.j ava 2 s . c o m * jarFile that will be checked for frontend files * * @return boolean */ private boolean hasFrontendFiles(JarFile jarFile) { Enumeration enums = jarFile.entries(); while (enums.hasMoreElements()) { JarEntry jarEntry = (JarEntry) enums.nextElement(); if (jarEntry.getName().contains(RESOURCES_FOLDER) && jarEntry.isDirectory()) { return true; } } return false; }
From source file:com.cloudbees.sdk.ArtifactInstallFactory.java
/** * Installs the given artifact and all its transitive dependencies *//* w ww. ja v a 2 s .com*/ public GAV install(GAV gav) throws Exception { Artifact a = toArtifact(gav); List<ArtifactResult> artifactResults = repo.get().resolveDependencies(gav).getArtifactResults(); Plugin plugin = new Plugin(); List<CommandProperties> command = plugin.getProperties(); List<String> jars = plugin.getJars(); List<URL> urls = new ArrayList<URL>(); for (ArtifactResult artifactResult : artifactResults) { URL artifactURL = artifactResult.getArtifact().getFile().toURI().toURL(); urls.add(artifactURL); jars.add(artifactResult.getArtifact().getFile().getAbsolutePath()); } ClassLoader cl = createClassLoader(urls, getClass().getClassLoader()); for (ArtifactResult artifactResult : artifactResults) { if (toString(artifactResult.getArtifact()).equals(toString(a))) { plugin.setArtifact(new GAV(artifactResult.getArtifact().toString()).toString()); // System.out.println("Analysing... " + plugin.getArtifact()); JarFile jarFile = new JarFile(artifactResult.getArtifact().getFile()); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); if (entry.getName().endsWith(".class")) { String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); Class c = Class.forName(className, false, cl); findCommand(true, command, c); } } } } XStream xStream = new XStream(); xStream.processAnnotations(Plugin.class); xStream.processAnnotations(CommandProperties.class); // System.out.println(xStream.toXML(plugin)); File xmlFile = new File(directoryStructure.getPluginDir(), a.getArtifactId() + ".bees"); OutputStreamWriter fos = null; try { xmlFile.getParentFile().mkdirs(); FileOutputStream outputStream = new FileOutputStream(xmlFile); fos = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); xStream.toXML(plugin, fos); } finally { IOUtils.closeQuietly(fos); } return new GAV(plugin.getArtifact()); }
From source file:org.rhq.enterprise.server.plugin.pc.perspective.PerspectiveServerPluginManager.java
private void undeployWars(ServerPluginEnvironment env) { String name = null;/* w ww.j a va 2 s . c o m*/ try { JarFile plugin = new JarFile(env.getPluginUrl().getFile()); try { for (JarEntry entry : Collections.list(plugin.entries())) { name = entry.getName(); if (name.toLowerCase().endsWith(".war")) { undeployWar(getDeployFile(env, entry.getName())); } } } finally { plugin.close(); } } catch (Exception e) { this.log.error("Failed to deploy " + env.getPluginKey().getPluginName() + "#" + name, e); } }
From source file:org.abs_models.backend.erlang.ErlApp.java
private void copyJarDirectory(JarFile jarFile, String inname, String outname) throws IOException { InputStream is = null;/*from ww w. j a v a 2 s . c o m*/ for (JarEntry entry : Collections.list(jarFile.entries())) { if (entry.getName().startsWith(inname)) { String relFilename = entry.getName().substring(inname.length()); if (!entry.isDirectory()) { is = jarFile.getInputStream(entry); ByteStreams.copy(is, Files.asByteSink(new File(outname, relFilename)).openStream()); } else { new File(outname, relFilename).mkdirs(); } } } is.close(); }