List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:org.apache.tajo.util.ClassUtil.java
private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars, @Nullable Class type, String packageFilter, @Nullable Predicate predicate) { if (file.isDirectory()) { for (File child : file.listFiles()) { findClasses(matchedClassSet, root, child, includeJars, type, packageFilter, predicate); }/*from w ww . j ava 2 s .co m*/ } else { if (file.getName().toLowerCase().endsWith(".jar") && includeJars) { JarFile jar = null; try { jar = new JarFile(file); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); return; } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); int extIndex = name.lastIndexOf(".class"); if (extIndex > 0) { String qualifiedClassName = name.substring(0, extIndex).replace("/", "."); if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) { try { Class clazz = Class.forName(qualifiedClassName); if (isMatched(clazz, type, predicate)) { matchedClassSet.add(clazz); } } catch (ClassNotFoundException e) { LOG.error(e.getMessage(), e); } } } } try { jar.close(); } catch (IOException e) { LOG.warn("Closing " + file.getName() + " was failed."); } } else if (file.getName().toLowerCase().endsWith(".class")) { String qualifiedClassName = createClassName(root, file); if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) { try { Class clazz = Class.forName(qualifiedClassName); if (isMatched(clazz, type, predicate)) { matchedClassSet.add(clazz); } } catch (ClassNotFoundException e) { LOG.error(e.getMessage(), e); } } } } }
From source file:org.eclipse.wb.internal.swing.laf.LafUtils.java
/** * Opens given <code>jarFile</code>, loads every class inside own {@link ClassLoader} and checks * loaded class for to be instance of {@link LookAndFeel}. Returns the array of {@link LafInfo} * containing all found {@link LookAndFeel} classes. * /*from www .jav a 2 s .c om*/ * @param jarFileName * the absolute OS path pointing to source JAR file. * @param monitor * the progress monitor which checked for interrupt request. * @return the array of {@link UserDefinedLafInfo} containing all found {@link LookAndFeel} * classes. */ public static UserDefinedLafInfo[] scanJarForLookAndFeels(String jarFileName, IProgressMonitor monitor) throws Exception { List<UserDefinedLafInfo> lafList = Lists.newArrayList(); File jarFile = new File(jarFileName); URLClassLoader ucl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }); JarFile jar = new JarFile(jarFile); Enumeration<?> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); if (entry.isDirectory() || !entryName.endsWith(".class") || entryName.indexOf('$') >= 0) { continue; } String className = entryName.replace('/', '.').replace('\\', '.'); className = className.substring(0, className.lastIndexOf('.')); Class<?> clazz = null; try { clazz = ucl.loadClass(className); } catch (Throwable e) { continue; } // check loaded class to be a non-abstract subclass of javax.swing.LookAndFeel class if (LookAndFeel.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) { // use the class name as name of LAF String shortClassName = CodeUtils.getShortClass(className); // strip trailing "LookAndFeel" String lafName = StringUtils.chomp(shortClassName, "LookAndFeel"); lafList.add(new UserDefinedLafInfo(StringUtils.isEmpty(lafName) ? shortClassName : lafName, className, jarFileName)); } // check for Cancel button pressed if (monitor.isCanceled()) { return lafList.toArray(new UserDefinedLafInfo[lafList.size()]); } // update ui while (DesignerPlugin.getStandardDisplay().readAndDispatch()) { } } return lafList.toArray(new UserDefinedLafInfo[lafList.size()]); }
From source file:com.eviware.soapui.plugins.JarClassLoader.java
public JarClassLoader(File jarFile, ClassLoader parent, Collection<JarClassLoader> dependencyClassLoaders) throws IOException { super(new URL[] { jarFile.toURI().toURL() }, null); this.parent = parent; this.dependencyClassLoaders = dependencyClassLoaders; JarFile file = new JarFile(jarFile); addLibrariesIn(file);//from w ww.j a v a 2s. co m addScriptsIn(file); }
From source file:net.minecraftforge.fml.common.discovery.JarDiscoverer.java
@Override public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table) { List<ModContainer> foundMods = Lists.newArrayList(); FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName()); JarFile jar = null;/* www . j av a 2s. c om*/ try { jar = new JarFile(candidate.getModContainer()); ZipEntry modInfo = jar.getEntry("mcmod.info"); MetadataCollection mc = null; if (modInfo != null) { FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName()); InputStream inputStream = jar.getInputStream(modInfo); try { mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName()); } finally { IOUtils.closeQuietly(inputStream); } } else { FMLLog.fine("The mod container %s appears to be missing an mcmod.info file", candidate.getModContainer().getName()); mc = MetadataCollection.from(null, ""); } for (ZipEntry ze : Collections.list(jar.entries())) { if (ze.getName() != null && ze.getName().startsWith("__MACOSX")) { continue; } Matcher match = classFile.matcher(ze.getName()); if (match.matches()) { ASMModParser modParser; try { InputStream inputStream = jar.getInputStream(ze); try { modParser = new ASMModParser(inputStream); } finally { IOUtils.closeQuietly(inputStream); } candidate.addClassEntry(ze.getName()); } catch (LoaderException e) { FMLLog.log(Level.ERROR, e, "There was a problem reading the entry %s in the jar %s - probably a corrupt zip", ze.getName(), candidate.getModContainer().getPath()); jar.close(); throw e; } modParser.validate(); modParser.sendToTable(table, candidate); ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate); if (container != null) { table.addContainer(container); foundMods.add(container); container.bindMetadata(mc); container.setClassVersion(modParser.getClassVersion()); } } } } catch (Exception e) { FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored", candidate.getModContainer().getName()); } finally { Java6Utils.closeZipQuietly(jar); } return foundMods; }
From source file:com.thoughtworks.go.agent.common.util.JarUtil.java
public static List<File> extractFilesInLibDirAndReturnFiles(File aJarFile, Predicate<JarEntry> extractFilter, File outputTmpDir) {/*w ww . j av a 2 s . c om*/ List<File> newClassPath = new ArrayList<>(); try (JarFile jarFile = new JarFile(aJarFile)) { List<File> extractedJars = jarFile.stream().filter(extractFilter).map(jarEntry -> { String jarFileBaseName = FilenameUtils.getName(jarEntry.getName()); File targetFile = new File(outputTmpDir, jarFileBaseName); return extractJarEntry(jarFile, jarEntry, targetFile); }).collect(Collectors.toList()); // add deps in dir specified by `libDirManifestKey` newClassPath.addAll(extractedJars); } catch (IOException e) { throw new RuntimeException(e); } return newClassPath; }
From source file:io.fabric8.vertx.maven.plugin.it.PackagingIT.java
@Test public void testContentInTheJar() throws IOException, VerificationException { File testDir = initProject(PACKAGING_META_INF); assertThat(testDir).isDirectory();//from ww w. j a va 2s . co m initVerifier(testDir); prepareProject(testDir, verifier); runPackage(verifier); assertThat(testDir).isNotNull(); File out = new File(testDir, "target/vertx-demo-start-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(out).isFile(); JarFile jar = new JarFile(out); // Commons utils // org.apache.commons.io.CopyUtils JarEntry entry = jar.getJarEntry("org/apache/commons/io/CopyUtils.class"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // SLF4J-API // /org/slf4j/MDC.class entry = jar.getJarEntry("org/slf4j/MDC.class"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // tc native // /org/apache/tomcat/Apr.class entry = jar.getJarEntry("org/apache/tomcat/Apr.class"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // /org/apache/tomcat/apr.properties entry = jar.getJarEntry("org/apache/tomcat/apr.properties"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // /META-INF/native/libnetty-tcnative-linux-x86_64.so entry = jar.getJarEntry("META-INF/native/libnetty-tcnative-linux-x86_64.so"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // Jackson (transitive of vert.x core) // /com/fasterxml/jackson/annotation/JacksonAnnotation.class entry = jar.getJarEntry("com/fasterxml/jackson/annotation/JacksonAnnotation.class"); assertThat(entry).isNotNull(); assertThat(entry.isDirectory()).isFalse(); // Not included // codegen - transitive optional entry = jar.getJarEntry("io/vertx/codegen/Case.class"); assertThat(entry).isNull(); // log4j - transitive provided entry = jar.getJarEntry("org/apache/log4j/MDC.class"); assertThat(entry).isNull(); // junit - test entry = jar.getJarEntry("junit/runner/Version.class"); assertThat(entry).isNull(); // commons-lang3 - provided entry = jar.getJarEntry("org/apache/commons/lang3/RandomUtils.class"); assertThat(entry).isNull(); }
From source file:io.lightlink.utils.ClasspathScanUtils.java
public static List<String> getResourcesFromPackage(String packageName) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> packageURLs; ArrayList<String> names = new ArrayList<String>(); packageName = packageName.replace(".", "/"); packageURLs = classLoader.getResources(packageName); while (packageURLs.hasMoreElements()) { URL packageURL = packageURLs.nextElement(); // loop through files in classpath if (packageURL.getProtocol().equals("jar")) { String jarFileName;/* w ww. jav a 2s . c o m*/ JarFile jf; Enumeration<JarEntry> jarEntries; String entryName; // build jar file name, then loop through zipped entries jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8"); jarFileName = jarFileName.substring(5, jarFileName.indexOf("!")); jf = new JarFile(jarFileName); jarEntries = jf.entries(); while (jarEntries.hasMoreElements()) { entryName = jarEntries.nextElement().getName(); if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) { entryName = entryName.substring(packageName.length()); names.add(entryName); } } } else { findFromDirectory(packageURL, names); } } return names; }
From source file:eu.stratosphere.yarn.Utils.java
public static void copyJarContents(String prefix, String pathToJar) throws IOException { LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix); JarFile jar = null;//from www. ja v a 2 s . c om jar = new JarFile(pathToJar); Enumeration<JarEntry> enumr = jar.entries(); byte[] bytes = new byte[1024]; while (enumr.hasMoreElements()) { JarEntry entry = enumr.nextElement(); if (entry.getName().startsWith(prefix)) { if (entry.isDirectory()) { File cr = new File(entry.getName()); cr.mkdirs(); continue; } InputStream inStream = jar.getInputStream(entry); File outFile = new File(entry.getName()); if (outFile.exists()) { throw new RuntimeException("File unexpectedly exists"); } FileOutputStream outputStream = new FileOutputStream(outFile); int read = 0; while ((read = inStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } inStream.close(); outputStream.close(); } } jar.close(); }
From source file:org.eclipse.licensing.eclipse_licensing_plugin.InjectLicensingMojo.java
private void extractLicensingBaseFiles() throws IOException { JarFile jar = new JarFile(getLicensingBasePlugin()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName.startsWith("org")) { File file = new File(classesDirectory, entryName); if (entry.isDirectory()) { file.mkdir();/* w ww .j av a 2s .c o m*/ } else { InputStream is = jar.getInputStream(entry); FileOutputStream fos = new FileOutputStream(file); while (is.available() > 0) { fos.write(is.read()); } fos.close(); is.close(); } } } jar.close(); }
From source file:org.commonjava.maven.galley.filearc.internal.ZipDownload.java
@Override public DownloadJob call() { final File src = getZipFile(); if (src.isDirectory()) { return this; }//from w w w. ja va 2 s . com ZipFile zf = null; InputStream in = null; OutputStream out = null; try { zf = isJarOperation() ? new JarFile(src) : new ZipFile(src); final ZipEntry entry = zf.getEntry(getFullPath()); if (entry != null) { if (entry.isDirectory()) { error = new TransferException("Cannot read stream. Source is a directory: %s!%s", getLocation().getUri(), getFullPath()); } else { in = zf.getInputStream(entry); out = getTransfer().openOutputStream(TransferOperation.DOWNLOAD, true, eventMetadata); copy(in, out); return this; } } else { error = new TransferException("Cannot find entry: %s in: %s", getFullPath(), getLocation().getUri()); } } catch (final IOException e) { error = new TransferException("Failed to copy from: %s to: %s. Reason: %s", e, src, getTransfer(), e.getMessage()); } finally { closeQuietly(in); if (zf != null) { //noinspection EmptyCatchBlock try { zf.close(); } catch (final IOException e) { } } closeQuietly(out); } if (error != null) { logger.error("Failed to download: {}. Reason: {}", this, error); } return null; }