List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:javadepchecker.Main.java
private static boolean depsFound(Collection<String> pkgs, Collection<String> deps) throws IOException { boolean found = true; Collection<String> jars = new ArrayList<String>(); String[] bootClassPathJars = System.getProperty("sun.boot.class.path").split(":"); // Do we need "java-config -r" here? for (String jar : bootClassPathJars) { File jarFile = new File(jar); if (jarFile.exists()) { jars.add(jar);//from ww w. j a v a 2s .c o m } } for (Iterator<String> pkg = pkgs.iterator(); pkg.hasNext();) { jars.addAll(getPackageJars(pkg.next())); } if (jars.size() == 0) { return false; } ArrayList<String> jarClasses = new ArrayList<String>(); for (String jarName : jars) { JarFile jar = new JarFile(jarName); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { jarClasses.add(e.nextElement().getName()); } } for (String dep : deps) { if (!jarClasses.contains(dep)) { if (found) { System.out.println("Class files not found via DEPEND in package.env"); } System.out.println("\t" + dep); found = false; } } return found; }
From source file:org.shept.util.JarUtils.java
/** * Copy resources from a classPath, typically within a jar file * to a specified destination, typically a resource directory in * the projects webApp directory (images, sounds, e.t.c. ) * // w w w . j a v a 2 s . c om * Copies resources only if the destination file does not exist and * the specified resource is available. * * The ClassPathResource will be scanned for all resources in the path specified by the resource. * For example a path like: * new ClassPathResource("resource/images/pager/", SheptBaseController.class); * takes all the resources in the path 'resource/images/pager' (but not in sub-path) * from the specified clazz 'SheptBaseController' * * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar) * @param webAppDestPath Full path String to the fileSystem destination directory * @throws IOException when copying on copy error * @throws URISyntaxException */ public static void copyResources(ClassPathResource cpr, String webAppDestPath) throws IOException, URISyntaxException { String dstPath = webAppDestPath; // + "/" + jarPathInternal(cpr.getURL()); File dir = new File(dstPath); dir.mkdirs(); URL url = cpr.getURL(); // jarUrl is the URL of the containing lib, e.g. shept.org in this case URL jarUrl = ResourceUtils.extractJarFileURL(url); String urlFile = url.getFile(); String resPath = ""; int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR); if (separatorIndex != -1) { // just copy the the location path inside the jar without leading separators !/ resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length()); } else { return; // no resource within jar to copy } File f = new File(ResourceUtils.toURI(jarUrl)); JarFile jf = new JarFile(f); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String path = entry.getName(); if (path.startsWith(resPath) && entry.getSize() > 0) { String fileName = path.substring(path.lastIndexOf("/")); File dstFile = new File(dstPath, fileName); // (StringUtils.applyRelativePath(dstPath, fileName)); Resource fileRes = cpr.createRelative(fileName); if (!dstFile.exists() && fileRes.exists()) { FileOutputStream fos = new FileOutputStream(dstFile); FileCopyUtils.copy(fileRes.getInputStream(), fos); logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to " + dstFile.getPath()); } } } if (jf != null) { jf.close(); } }
From source file:com.npower.dm.msm.JADCreator.java
public SoftwareInformation getSoftwareInformation(File file) throws IOException { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); SoftwareInformation info = new SoftwareInformation(); info.setVendor(manifest.getMainAttributes().getValue("MIDlet-Vendor")); info.setName(manifest.getMainAttributes().getValue("MIDlet-Name")); info.setVersion(manifest.getMainAttributes().getValue("MIDlet-Version")); String midpVersion = manifest.getMainAttributes().getValue("MicroEdition-Profile"); if (StringUtils.isNotEmpty(midpVersion) && midpVersion.trim().equalsIgnoreCase("MIDP-2.0")) { info.setMidp2(true);//from w w w . j a va2 s. c om } return info; }
From source file:javadepchecker.Main.java
/** * Check if a dependency is needed by a given package * * @param pkg Gentoo package name//from w w w .ja v a 2 s . c o m * @param deps collection of dependencies for the package * @return boolean if the dependency is needed or not * @throws IOException */ private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException { Collection<String> jars = getPackageJars(pkg); // We have a virtual with VM provider here if (jars.isEmpty()) { return true; } for (String jarName : jars) { JarFile jar = new JarFile(jarName); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { String name = e.nextElement().getName(); if (deps.contains(name)) { return true; } } } return false; }
From source file:org.apache.hadoop.chukwa.hicc.HiccWebServer.java
public List<String> getResourceListing(String path) throws URISyntaxException, IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); URL dirURL = contextClassLoader.getResource(path); if (dirURL == null) { dirURL = contextClassLoader.getResource(path); }/*from w ww. j a v a 2s . c o m*/ if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar List<String> result = new ArrayList<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()); int checkSubdir = entry.indexOf("/"); if (checkSubdir == 0 && entry.length() > 1) { // if it is a subdirectory, we just return the directory name result.add(name); } } } return result; } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java
/** * Load resources from jars or directories * * @param resources found resources will be added to this collection * @param jarOrDir a File, can be a jar or a directory * @param filter used to filter resources *//* w w w. j a v a2 s.c om*/ private static void collectFiles(Collection resources, File jarOrDir, Filter filter) { if (!jarOrDir.exists()) { log.warn("missing file: {}", jarOrDir.getAbsolutePath()); return; } if (jarOrDir.isDirectory()) { if (log.isDebugEnabled()) log.debug("looking in dir {}", jarOrDir.getAbsolutePath()); Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() { }, new TrueFileFilter() { }); for (Iterator iter = files.iterator(); iter.hasNext();) { File file = (File) iter.next(); String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath()); // please, be kind to Windows!!! name = StringUtils.replace(name, "\\", "/"); if (!name.startsWith("/")) { name = "/" + name; } if (filter.accept(name)) { resources.add(name); } } } else if (jarOrDir.getName().endsWith(".jar")) { if (log.isDebugEnabled()) log.debug("looking in jar {}", jarOrDir.getAbsolutePath()); JarFile jar; try { jar = new JarFile(jarOrDir); } catch (IOException e) { log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath()); return; } for (Enumeration em = jar.entries(); em.hasMoreElements();) { JarEntry entry = (JarEntry) em.nextElement(); if (!entry.isDirectory()) { if (filter.accept("/" + entry.getName())) { resources.add("/" + entry.getName()); } } } } else { if (log.isDebugEnabled()) log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName()); } }
From source file:net.avalonrealms.plugins.core.Core.java
@Override public void onEnable() { // Folders/*from ww w .j ava 2s .c o m*/ downloadFolder = new File(getDataFolder(), "downloads"); errorFolder = new File(getDataFolder(), "errors"); addonFolder = new File(getDataFolder(), "addons"); repoFolder = new File(getDataFolder(), "repo"); // Make folders TODO check result downloadFolder.mkdirs(); errorFolder.mkdirs(); addonFolder.mkdirs(); repoFolder.mkdirs(); // Utils errorUtils = new ErrorUtils(this); hookUtils = new HookUtils(this); // Updater updater = new Updater(this); // CommandInfo map try { Class<?> craftServer = SVPTools.getCurrentCBClass("CraftServer"); if (craftServer == null) throw new RuntimeException("Computer says no to getting the craft server"); Field f = craftServer.getDeclaredField("commandMap"); f.setAccessible(true); commandMap = (CommandMap) f.get(getServer()); } catch (Exception e) { errorUtils.logError(e); getServer().getPluginManager().disablePlugin(this); return; } // Listeners PluginManager p = getServer().getPluginManager(); if (getHookUtils().isHooked(HookUtils.Hook.WORLD_GUARD)) { p.registerEvents(new WGListener(this, (com.sk89q.worldguard.bukkit.WorldGuardPlugin) getHookUtils() .getHook(HookUtils.Hook.WORLD_GUARD)), this); } else { getLogger().warning("WorldGuard was not found. WorldGuard events will not run."); } // Addons File[] addons = getAddonFolder().listFiles(); if (addons == null) { throw new RuntimeException("Unable to create addon directory"); } for (File file : addons) { if (file.isDirectory() || !file.getName().endsWith(".jar")) { continue; } try { ClasspathTools.addFileToClasspath(getClassLoader(), file); JarFile jar = new JarFile(file); Class<?> main = Class.forName(jar.getManifest().getMainAttributes().getValue("Addon-Package")); CoreAddon addon = (CoreAddon) main.newInstance(); addon.setManifestValues(jar.getManifest()); coreAddons.put(addon.getName(), addon); jar.close(); } catch (Exception e) { errorUtils.logError(e); } } for (CoreAddon addon : Maps.newHashMap(coreAddons).values()) { addon.initialise(this); addon.onEnable(); } getLogger().info("Enabled " + coreAddons.size() + " addons."); }
From source file:org.apache.hive.beeline.ClassNameCompleter.java
public static String[] getClassNames() throws IOException { Set urls = new HashSet(); for (ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader != null; loader = loader .getParent()) {//from w w w . j a v a2s .c o m if (!(loader instanceof URLClassLoader)) { continue; } urls.addAll(Arrays.asList(((URLClassLoader) loader).getURLs())); } // Now add the URL that holds java.lang.String. This is because // some JVMs do not report the core classes jar in the list of // class loaders. Class[] systemClasses = new Class[] { String.class, javax.swing.JFrame.class }; for (int i = 0; i < systemClasses.length; i++) { URL classURL = systemClasses[i] .getResource("/" + systemClasses[i].getName().replace('.', '/') + clazzFileNameExtension); if (classURL != null) { URLConnection uc = classURL.openConnection(); if (uc instanceof JarURLConnection) { urls.add(((JarURLConnection) uc).getJarFileURL()); } } } Set classes = new HashSet(); for (Iterator i = urls.iterator(); i.hasNext();) { URL url = (URL) i.next(); File file = new File(url.getFile()); if (file.isDirectory()) { Set files = getClassFiles(file.getAbsolutePath(), new HashSet(), file, new int[] { 200 }); classes.addAll(files); continue; } if ((file == null) || !file.isFile()) { continue; } JarFile jf = new JarFile(file); for (Enumeration e = jf.entries(); e.hasMoreElements();) { JarEntry entry = (JarEntry) e.nextElement(); if (entry == null) { continue; } String name = entry.getName(); if (isClazzFile(name)) { /* only use class file*/ classes.add(name); } else if (isJarFile(name)) { classes.addAll(getClassNamesFromJar(name)); } else { continue; } } } // now filter classes by changing "/" to "." and trimming the // trailing ".class" Set classNames = new TreeSet(); for (Iterator i = classes.iterator(); i.hasNext();) { String name = (String) i.next(); classNames.add(name.replace('/', '.').substring(0, name.length() - 6)); } return (String[]) classNames.toArray(new String[classNames.size()]); }
From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java
@Override protected URL findResource(String name) { URL ret = null;/*from w w w . ja v a 2 s . c om*/ JarFile jarFile = null; try { for (Resource entry : this.classPath) { if (entry.getFilename().toLowerCase().endsWith(".jar")) { jarFile = new JarFile(entry.getFile()); ZipEntry ze = jarFile.getEntry(name); jarFile.close(); if (ze != null) { ret = new URL("jar:" + entry.getURL() + "!/" + name); break; } } else { Resource file = entry.createRelative(name); if (file.exists()) { ret = file.getURL(); break; } } } } catch (IOException e) { throw new WMRuntimeException(e); } return ret; }
From source file:com.moss.nomad.core.runner.Runner.java
public Runner(File packageJar) throws Exception { log = LogFactory.getLog(this.getClass()); if (packageJar == null) { throw new NullPointerException(); }/*w w w .j av a2s . co m*/ this.packageJar = new JarFile(packageJar); context = JAXBContext.newInstance(MigrationHistory.class, MigrationContainer.class); container = extractContainer(packageJar); listeners = new ArrayList<RunListener>(); workDir = createTempDir(); }