List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.fengduo.bee.commons.core.utilities.ClassPathScanner.java
void findInJar(List<Class<?>> results, File file, String packageName) { JarFile jarFile = null;/* w w w. j a v a 2 s.c o m*/ String packagePath = dotToPath(packageName) + "/"; try { jarFile = new JarFile(file); Enumeration<JarEntry> en = jarFile.entries(); while (en.hasMoreElements()) { JarEntry je = en.nextElement(); String name = je.getName(); if (name.startsWith(packagePath) && name.endsWith(CLASS_FILE)) { String className = name.substring(0, name.length() - CLASS_FILE.length()); add(results, pathToDot(className)); } } } catch (IOException e) { e.printStackTrace(); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { } } } }
From source file:net.dries007.coremod.Module.java
/** * This method gets all the dependencies, ASM classes and ATs from the files associated with this module. */// w w w . j ava 2 s. com public void parceJarFiles() { for (ModuleFile mFile : this.files) { try { JarFile jar = new JarFile(mFile.file); Manifest mf = jar.getManifest(); if (mf != null) { for (Entry<Object, Object> attribute : mf.getMainAttributes().entrySet()) { attributes.put(attribute.getKey().toString(), attribute.getValue().toString()); } /** * Reading NORMAL libs from the modules' manifest files. * We want: Space sperated pairs of filename:sha1 */ if (Data.hasKey(Data.LIBKEY_NORMAL, Data.LIBURL_NORMAL)) { String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_NORMAL)); if (libs != null) for (String lib : libs.split(" ")) { DefaultDependency dependency = new DefaultDependency(lib); dependecies.add(dependency); } } /** * Reading MAVEN libs from the modules' manifest files. * We want: the maven name */ if (Data.hasKey(Data.LIBKEY_MAVEN, Data.LIBURL_MAVEN)) { String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_MAVEN)); if (libs != null) for (String lib : libs.split(" ")) { MavenDependency dependency = new MavenDependency(this, lib); dependecies.add(dependency); dependecies.addAll(Coremod.getDependencies(dependency)); } } /* * Reading ASM classes from the modules' manifest files */ if (Data.hasKey(Data.CLASSKEY_ASM)) { String asmclasses = mf.getMainAttributes().getValue(Data.get(Data.CLASSKEY_ASM)); if (asmclasses != null) for (String asmclass : asmclasses.split(" ")) { this.ASMClasses.add(asmclass); System.out.println("[" + Data.NAME + "] Added ASM class (" + asmclass + ") for module file " + jar.getName()); } } /* * Reading AT Files from the modules' manifest files */ if (Data.hasKey(Data.FILEKEY_TA)) { String ats = mf.getMainAttributes().getValue(Data.FILEKEY_TA); if (ats != null) for (String at : ats.split(" ")) { this.ATFiles.add(at); System.out.println("[" + Data.NAME + "] Added AccessTransformer (" + at + ") for module file " + jar.getName()); } } } jar.close(); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } } }
From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java
@Override protected InputStream createPackStream(File source) throws IOException { File tmpfile = null;//from w w w . j a v a 2 s . c o m JarFile jar = null; try { tmpfile = File.createTempFile("izpack-compress", ".pack200", FileUtils.getTempDirectory()); CountingOutputStream proxyOutputStream = new CountingOutputStream(FileUtils.openOutputStream(tmpfile)); OutputStream bufferedStream = IOUtils.buffer(proxyOutputStream); Pack200.Packer packer = createPack200Packer(this.packFile); jar = new JarFile(this.packFile.getFile()); packer.pack(jar, bufferedStream); bufferedStream.flush(); this.packFile.setSize(proxyOutputStream.getByteCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(FileUtils.openInputStream(tmpfile), out); out.close(); return new ByteArrayInputStream(out.toByteArray()); } finally { if (jar != null) { jar.close(); } FileUtils.deleteQuietly(tmpfile); } }
From source file:dk.netarkivet.common.utils.batch.ByteJarLoader.java
/** * Constructor for the ByteLoader./*from w w w. j av a 2s .c o m*/ * * @param files * An array of files, which are assumed to be jar-files, but * they need not have the extension .jar */ public ByteJarLoader(File... files) { ArgumentNotValid.checkNotNull(files, "File ... files"); ArgumentNotValid.checkTrue(files.length != 0, "Should not be empty array"); for (File file : files) { try { JarFile jarFile = new JarFile(file); for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); String name = entry.getName(); InputStream in = jarFile.getInputStream(entry); ByteArrayOutputStream out = new ByteArrayOutputStream((int) entry.getSize()); StreamUtils.copyInputStreamToOutputStream(in, out); log.trace("Entering data for class '" + name + "'"); binaryData.put(name, out.toByteArray()); } } catch (IOException e) { throw new IOFailure("Failed to load jar file '" + file.getAbsolutePath() + "': " + e); } } }
From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java
public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException { try {/* ww w.j a v a 2 s.c om*/ ArrayList<Class> classes = new ArrayList<Class>(); URLClassLoader ucl = (URLClassLoader) cl; URL[] srcURL = ucl.getURLs(); String path = pkg.replace('.', '/'); //Read resources as URL from class loader. for (URL url : srcURL) { if ("file".equals(url.getProtocol())) { File f = new File(url.toURI().getPath()); //If file is not of type directory then its a jar file if (f.exists() && !f.isDirectory()) { try { JarFile jf = new JarFile(f); Enumeration<JarEntry> entries = jf.entries(); //read all entries in jar file while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String clazzName = je.getName(); if (clazzName != null && clazzName.endsWith(".class")) { //Add to class list here. clazzName = clazzName.substring(0, clazzName.length() - 6); clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.'); //We are only going to add the class that belong to the provided package. if (clazzName.startsWith(pkg + ".")) { try { Class clazz = forName(clazzName, false, cl); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg) && ClassUtils.getDefaultPublicConstructor(clazz) != null && !ClassUtils.isJAXWSClass(clazz)) { if (log.isDebugEnabled()) { log.debug("Adding class: " + clazzName); } classes.add(clazz); } //catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception, so lets catch everything that extends Throwable //rather than just Exception. } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + clazzName + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } catch (IOException e) { throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4")); } } } } return classes; } catch (Exception e) { throw new ClassNotFoundException(e.getMessage()); } }
From source file:uk.codingbadgers.bootstrap.tasks.TaskInstallerUpdateCheck.java
@Override public void run(Bootstrap bootstrap) { try {/*from w w w .ja v a 2 s . c o m*/ HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(INSTALLER_UPDATE_URL); request.setHeader(new BasicHeader("Accept", GITHUB_MIME_TYPE)); HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String localVersion = null; if (bootstrap.getInstallerFile().exists()) { JarFile jar = new JarFile(bootstrap.getInstallerFile()); Manifest manifest = jar.getManifest(); localVersion = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); jar.close(); } JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray(); JsonObject release = json.get(0).getAsJsonObject(); JsonObject installerAsset = null; JsonObject librariesAsset = null; int i = 0; for (JsonElement element : release.get("assets").getAsJsonArray()) { JsonObject object = element.getAsJsonObject(); if (INSTALLER_LABEL.equals(object.get("name").getAsString())) { installerAsset = object; } else if (INSTALLER_LIBS_LABEL.equals(object.get("name").getAsString())) { librariesAsset = object; } } if (VersionComparator.getInstance().compare(localVersion, release.get("name").getAsString()) < 0) { bootstrap.addDownload(DownloadType.INSTALLER, new EtagDownload( installerAsset.get("url").getAsString(), bootstrap.getInstallerFile())); localVersion = release.get("name").getAsString(); } File libs = new File(bootstrap.getInstallerFile() + ".libs"); boolean update = true; if (libs.exists()) { FileReader reader = null; try { reader = new FileReader(libs); JsonElement parsed = PARSER.parse(reader); if (parsed.isJsonObject()) { JsonObject libsJson = parsed.getAsJsonObject(); if (libsJson.has("installer")) { JsonObject installerJson = libsJson.get("installer").getAsJsonObject(); if (installerJson.get("version").getAsString().equals(localVersion)) { update = false; } } } } catch (JsonParseException ex) { throw new BootstrapException(ex); } finally { reader.close(); } } if (update) { new EtagDownload(librariesAsset.get("url").getAsString(), new File(bootstrap.getInstallerFile() + ".libs")).download(); FileReader reader = null; FileWriter writer = null; try { reader = new FileReader(libs); JsonObject libsJson = PARSER.parse(reader).getAsJsonObject(); JsonObject versionJson = new JsonObject(); versionJson.add("version", new JsonPrimitive(localVersion)); libsJson.add("installer", versionJson); writer = new FileWriter(libs); new Gson().toJson(libsJson, writer); } catch (JsonParseException ex) { throw new BootstrapException(ex); } finally { reader.close(); writer.close(); } } EntityUtils.consume(entity); } else if (statusLine.getStatusCode() == HttpStatus.SC_FORBIDDEN) { System.err.println("Hit rate limit, skipping update check"); } else { throw new BootstrapException("Error sending request to github. Error " + statusLine.getStatusCode() + statusLine.getReasonPhrase()); } } catch (IOException e) { throw new BootstrapException(e); } }
From source file:org.echocat.nodoodle.classloading.FileClassLoader.java
public FileClassLoader(Iterable<File> classPath, ClassLoader parent) throws IOException { super(parent); if (classPath == null) { throw new NullPointerException("The parameter files is null."); }//from w w w.j a v a 2s .co m final Collection<JarFile> jarFiles = new ArrayList<JarFile>(); final Collection<File> directories = new ArrayList<File>(); for (File classPathPart : classPath) { if (classPathPart.isDirectory()) { directories.add(classPathPart); } else { final JarFile jarFile = new JarFile(classPathPart); jarFiles.add(jarFile); } } _jarFiles = Collections.unmodifiableCollection(jarFiles); _directories = Collections.unmodifiableCollection(directories); }
From source file:com.twosigma.beaker.autocomplete.ClasspathScanner.java
private boolean findClasses(File root, File file, boolean includeJars) { if (file != null && file.isDirectory()) { File[] lf = file.listFiles(); if (lf != null) for (File child : lf) { if (!findClasses(root, child, includeJars)) { return false; }// ww w . j ava 2 s . c o m } } else { if (file.getName().toLowerCase().endsWith(".jar") && includeJars) { JarFile jar = null; try { jar = new JarFile(file); } catch (Exception ex) { } if (jar != null) { try { Manifest mf = jar.getManifest(); if (mf != null) { String cp = mf.getMainAttributes().getValue("Class-Path"); if (StringUtils.isNotEmpty(cp)) { for (String fn : cp.split(" ")) { File child = new File( file.getParent() + System.getProperty("file.separator") + fn); if (child.getAbsolutePath().equals(jar.getName())) { continue; //skip bad jars, that contain references to themselves in MANIFEST.MF } if (child.exists()) { if (!findClasses(root, child, includeJars)) { return false; } } } } } } catch (IOException e) { } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); int extIndex = name.lastIndexOf(".class"); if (extIndex > 0 && !name.contains("$")) { String cname = name.substring(0, extIndex).replace("/", "."); int pIndex = cname.lastIndexOf('.'); if (pIndex > 0) { String pname = cname.substring(0, pIndex); cname = cname.substring(pIndex + 1); if (!packages.containsKey(pname)) packages.put(pname, new ArrayList<String>()); packages.get(pname).add(cname); } } } } } else if (file.getName().toLowerCase().endsWith(".class")) { String cname = createClassName(root, file); if (!cname.contains("$")) { int pIndex = cname.lastIndexOf('.'); if (pIndex > 0) { String pname = cname.substring(0, pIndex + 1); cname = cname.substring(pIndex); if (!packages.containsKey(pname)) packages.put(pname, new ArrayList<String>()); packages.get(pname).add(cname); } } } else { examineFile(root, file); } } return true; }
From source file:com.twosigma.beakerx.autocomplete.ClasspathScanner.java
private boolean findClasses(File root, File file, boolean includeJars) { if (file != null && file.isDirectory()) { File[] lf = file.listFiles(); if (lf != null) for (File child : lf) { if (!findClasses(root, child, includeJars)) { return false; }/*from w ww.j a v a 2 s . co m*/ } } else { if (file.getName().toLowerCase().endsWith(".jar") && includeJars) { JarFile jar = null; try { jar = new JarFile(file); } catch (Exception ex) { } if (jar != null) { try { Manifest mf = jar.getManifest(); if (mf != null) { String cp = mf.getMainAttributes().getValue("Class-Path"); if (StringUtils.isNotEmpty(cp)) { for (String fn : cp.split(" ")) { if (!fn.equals(".")) { File child = new File( file.getParent() + System.getProperty("file.separator") + fn); if (child.getAbsolutePath().equals(jar.getName())) { continue; //skip bad jars, that contain references to themselves in MANIFEST.MF } if (child.exists()) { if (!findClasses(root, child, includeJars)) { return false; } } } } } } } catch (IOException e) { } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); int extIndex = name.lastIndexOf(".class"); if (extIndex > 0 && !name.contains("$")) { String cname = name.substring(0, extIndex).replace("/", "."); int pIndex = cname.lastIndexOf('.'); if (pIndex > 0) { String pname = cname.substring(0, pIndex); cname = cname.substring(pIndex + 1); if (!packages.containsKey(pname)) packages.put(pname, new ArrayList<String>()); packages.get(pname).add(cname); } } } } } else if (file.getName().toLowerCase().endsWith(".class")) { String cname = createClassName(root, file); if (!cname.contains("$")) { int pIndex = cname.lastIndexOf('.'); if (pIndex > 0) { String pname = cname.substring(0, pIndex + 1); cname = cname.substring(pIndex); if (!packages.containsKey(pname)) packages.put(pname, new ArrayList<String>()); packages.get(pname).add(cname); } } } else { examineFile(root, file); } } return true; }
From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java
@Test public void relocatedClasses() throws Exception { SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, Arrays.asList("org.foo.exclude.*")); List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator); String content = "org.foo.Service\norg.foo.exclude.OtherService\n"; byte[] contentBytes = content.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentResource = "META-INF/services/org.foo.something.another"; String contentResourceShaded = "META-INF/services/borg.foo.something.another"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); xformer.processResource(contentResource, contentStream, relocators); contentStream.close();//from w w w. j a v a2 s. co m File tempJar = File.createTempFile("shade.", ".jar"); tempJar.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tempJar); JarOutputStream jos = new JarOutputStream(fos); try { xformer.modifyOutputStream(jos, false); jos.close(); jos = null; JarFile jarFile = new JarFile(tempJar); JarEntry jarEntry = jarFile.getJarEntry(contentResourceShaded); assertNotNull(jarEntry); InputStream entryStream = jarFile.getInputStream(jarEntry); try { String xformedContent = IOUtils.toString(entryStream, "utf-8"); assertEquals("borg.foo.Service" + System.getProperty("line.separator") + "org.foo.exclude.OtherService" + System.getProperty("line.separator"), xformedContent); } finally { IOUtils.closeQuietly(entryStream); jarFile.close(); } } finally { if (jos != null) { IOUtils.closeQuietly(jos); } tempJar.delete(); } }