@Override public PluginDescription getPluginDescription(File file) { try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("nukkit.yml"); if (entry == null) { entry = jar.getJarEntry("plugin.yml"); if (entry == null) { return null; } } try (InputStream stream = jar.getInputStream(entry)) { return new PluginDescription(Utils.readFile(stream)); } } catch (IOException e) { return null; } }
private static void signWithJarSignerAPI(String jarName) throws Throwable { // Get JarSigner try (FileInputStream fis = new FileInputStream(KEYSTORE)) { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(fis, STOREPASS.toCharArray()); PrivateKey pk = (PrivateKey)ks.getKey(ALIAS, KEYPASS.toCharArray()); Certificate cert = ks.getCertificate(ALIAS); JarSigner signer = new JarSigner.Builder(pk, CertificateFactory.getInstance("X.509").generateCertPath( Collections.singletonList(cert))) .build(); // Sign jar try (ZipFile src = new JarFile(jarName); FileOutputStream out = new FileOutputStream(SIGNED_JAR)) { signer.sign(src,out); } } }
@Override public Object getBuildDocHandler(ClassLoader docsClassLoader, Iterable<File> classpath) throws NoSuchMethodException, ClassNotFoundException, IOException, IllegalAccessException { Class<?> docHandlerFactoryClass = getDocHandlerFactoryClass(docsClassLoader); Method docHandlerFactoryMethod = docHandlerFactoryClass.getMethod("fromJar", JarFile.class, String.class); JarFile documentationJar = findDocumentationJar(classpath); try { return docHandlerFactoryMethod.invoke(null, documentationJar, "play/docs/content"); } catch (InvocationTargetException e) { throw UncheckedException.unwrapAndRethrow(e); } }
public static void jarDir(File dir, String relativePath, ZipOutputStream zos) throws IOException { Preconditions.checkNotNull(relativePath, "relativePath"); Preconditions.checkNotNull(zos, "zos"); // by JAR spec, if there is a manifest, it must be the first entry in the // ZIP. File manifestFile = new File(dir, JarFile.MANIFEST_NAME); ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); if (!manifestFile.exists()) { zos.putNextEntry(manifestEntry); new Manifest().write(new BufferedOutputStream(zos)); zos.closeEntry(); } else { copyToZipStream(manifestFile, manifestEntry, zos); } zos.closeEntry(); zipDir(dir, relativePath, zos, true); zos.close(); }
private static void computeFieldMatches(File memberMatchesFile, JarFile destJar, File destMappingsFile, File classMatchesFile) throws IOException, MappingParseException { System.out.println("Reading class matches..."); ClassMatches classMatches = MatchesReader.readClasses(classMatchesFile); System.out.println("Reading mappings..."); Mappings destMappings = new MappingsReader().read(new FileReader(destMappingsFile)); System.out.println("Indexing dest jar..."); Deobfuscator destDeobfuscator = new Deobfuscator(destJar); System.out.println("Writing matches..."); // get the matched and unmatched mappings MemberMatches<FieldEntry> fieldMatches = MappingsConverter.computeMemberMatches( destDeobfuscator, destMappings, classMatches, MappingsConverter.getFieldDoer() ); MatchesWriter.writeMembers(fieldMatches, memberMatchesFile); System.out.println("Wrote:\n\t" + memberMatchesFile.getAbsolutePath()); }
void loadCorePlugin(File file, CaoutchoucClassLoader classLoader) { try { JarFile jarFile = new JarFile(file); Manifest manifest = jarFile.getManifest(); if(manifest == null) throw new FileNotFoundException("Jar does not contain manifest"); String corePlugin = manifest.getMainAttributes().getValue("corePlugin"); if(corePlugin == null) throw new IllegalArgumentException("Manifest does not contain \"corePlugin\" tag"); Caoutchouc.addInClassLoader(file); Class<?> corePluginClass = Class.forName(corePlugin, false, classLoader); if(ICorePlugin.class.isAssignableFrom(corePluginClass)) this.corePluginsClass.add(corePluginClass); } catch(Exception exc) { System.err.println(String.format("Unable to load core plugin %s", file.getName())); exc.printStackTrace(); } }
static void generateLargeJar(File result, File source) throws IOException { if (result.exists()) { result.delete(); } try (JarOutputStream copyTo = new JarOutputStream(new FileOutputStream(result)); JarFile srcJar = new JarFile(source)) { for (JarEntry je : Collections.list(srcJar.entries())) { copyTo.putNextEntry(je); if (!je.isDirectory()) { copyStream(srcJar.getInputStream(je), copyTo); } copyTo.closeEntry(); } int many = Short.MAX_VALUE * 2 + 2; for (int i = 0 ; i < many ; i++) { JarEntry e = new JarEntry("F-" + i + ".txt"); copyTo.putNextEntry(e); } copyTo.flush(); copyTo.close(); } }
protected static File changeManifest(File dir, String newName, File orig, String manifest) throws IOException { File f = new File(dir, newName); Manifest mf = new Manifest(new ByteArrayInputStream(manifest.getBytes("utf-8"))); mf.getMainAttributes().putValue("Manifest-Version", "1.0"); JarOutputStream os = new JarOutputStream(new FileOutputStream(f), mf); JarFile jf = new JarFile(orig); Enumeration<JarEntry> en = jf.entries(); InputStream is; while (en.hasMoreElements()) { JarEntry e = en.nextElement(); if (e.getName().equals("META-INF/MANIFEST.MF")) { continue; } os.putNextEntry(e); is = jf.getInputStream(e); FileUtil.copy(is, os); is.close(); os.closeEntry(); } os.close(); return f; }
/** * 获取dex2文件的SHA1-Digest值 * * @param context * @return */ private String get2thDexSHA1(Context context) { ApplicationInfo info = context.getApplicationInfo(); String source = info.sourceDir; try { JarFile jar = new JarFile(source); Manifest mf = jar.getManifest(); Map<String, Attributes> map = mf.getEntries(); Attributes a = map.get("classes2.dex"); return a.getValue("SHA1-Digest"); } catch (Exception e) { e.printStackTrace(); } return null; }
private void loadLocalizedBundlesFromPlatform(final BrandableModule moduleEntry, final String bundleEntry, final Set<String> keys, final Set<BundleKey> bundleKeys) throws IOException { Properties p = new Properties(); JarFile module = new JarFile(moduleEntry.getJarLocation()); JarEntry je = module.getJarEntry(bundleEntry); InputStream is = module.getInputStream(je); File bundle = new File(getModuleEntryDirectory(moduleEntry),bundleEntry); try { p.load(is); } finally { is.close(); } for (String key : NbCollections.checkedMapByFilter(p, String.class, String.class, true).keySet()) { if (keys.contains(key)) { String value = p.getProperty(key); bundleKeys.add(new BundleKey(moduleEntry, bundle, key, value)); } } }
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException { if (in.getManifest() != null) { ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME); out.putNextEntry(me); in.getManifest().write(out); out.closeEntry(); } byte[] buffer = new byte[1 << 14]; for (JarEntry je; (je = in.getNextJarEntry()) != null; ) { out.putNextEntry(je); for (int nr; 0 < (nr = in.read(buffer)); ) { out.write(buffer, 0, nr); } } in.close(); markJarFile(out); // add PACK200 comment }
/** * Get classes.dex file signature * * @param context * @return */ private String get2thDexSHA1(Context context) { ApplicationInfo ai = context.getApplicationInfo(); String source = ai.sourceDir; try { JarFile jar = new JarFile(source); java.util.jar.Manifest mf = jar.getManifest(); Map<String, Attributes> map = mf.getEntries(); Attributes a = map.get("classes2.dex"); if(a!=null){ return a.getValue("SHA1-Digest"); } } catch (Exception e) { e.printStackTrace(); } return null; }
@Test public void testNames() throws Exception { String rname = "version/Version.class"; String vname = "META-INF/versions/9/version/Version.class"; ZipEntry ze1; ZipEntry ze2; try (JarFile jf = new JarFile(multirelease)) { ze1 = jf.getEntry(vname); } Assert.assertEquals(ze1.getName(), vname); try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ, Runtime.Version.parse("9"))) { ze2 = jf.getEntry(rname); } Assert.assertEquals(ze2.getName(), rname); Assert.assertNotEquals(ze1.getName(), ze2.getName()); }
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { InputStream in = null; if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { throw new FileNotFoundException(Localizer.getMessage( "jsp.error.file.not.found", fname)); } return in; }
static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception { try (JarFile jf = new JarFile(file)) { JarEntry je = jf.getJarEntry("META-INF/OLD.RSA"); try (InputStream is = jf.getInputStream(je)) { byte[] content = IOUtils.readFully(is, -1, true); PKCS7 p7 = new PKCS7(content); SignerInfo[] si = p7.getSignerInfos(); if (si == null || si.length == 0) { throw new Exception("Not signed"); } PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes() .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID); PKCS7 tsToken = new PKCS7((byte[]) p9.getValue()); TimestampToken tt = new TimestampToken(tsToken.getContentInfo().getData()); if (!tt.getHashAlgorithm().toString().equals(digestAlg)) { throw new Exception("Digest alg different"); } if (!tt.getPolicyID().equals(policyId)) { throw new Exception("policyId different"); } } } }
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException { URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName); String internalClassName = classUri.getPath().substring(1); JarFile jarFile = null; try { for (int i = 0; i < jarFiles.size(); i++) { jarFile = jarFiles.get(i); JarEntry jarEntry = jarFile.getJarEntry(internalClassName); if (jarEntry != null) { InputStream inputStream = jarFile.getInputStream(jarEntry); try { byte[] byteCode = new byte[(int) jarEntry.getSize()]; ByteStreams.read(inputStream, byteCode, 0, byteCode.length); return defineClass(qualifiedClassName, byteCode, 0, byteCode.length); } finally { Closeables.closeQuietly(inputStream); } } } } catch (IOException e) { throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e); } return null; }
/** * get all class from jar * @param jarPath * @param classLoader * @return * @throws IOException * @throws ClassNotFoundException */ public static Set<Class<?>> getClassFromJar(String jarPath, DynamicClassLoader classLoader) throws IOException, ClassNotFoundException { JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.endsWith(".class")) { String className = name.replaceAll(".class", "").replaceAll("/", "."); Class<?> cls = null; try { // cls = classLoader.findClass(className); cls = classLoader.loadClass(className); } catch (Throwable ex) { } if (cls != null) { classes.add(cls); } } } return classes; }
private boolean isSigned(final JarFile jar) throws IOException { Enumeration<JarEntry> entries = jar.entries(); boolean signatureInfoPresent = false; boolean signatureFilePresent = false; while (entries.hasMoreElements()) { String entryName = entries.nextElement().getName(); if (entryName.startsWith("META-INF/")) { if (entryName.endsWith(".RSA") || entryName.endsWith(".DSA")) { signatureFilePresent = true; if (signatureInfoPresent) { break; } } else if (entryName.endsWith(".SF")) { signatureInfoPresent = true; if (signatureFilePresent) { break; } } } } return signatureFilePresent && signatureInfoPresent; }
/** * Returns the set of all packages on the given class path. */ Set<String> findPackages(List<Path> classpath) { Set<String> packages = new HashSet<>(); for (Path path : classpath) { if (Files.isDirectory(path)) { packages.addAll(findPackages(path)); } else if (Files.isRegularFile(path) && path.toString().endsWith(".jar")) { try (JarFile jf = new JarFile(path.toString())) { packages.addAll(findPackages(jf)); } catch (ZipException x) { // Skip. Do nothing. No packages will be added. } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } } return packages; }
private static void zipDir(File dir, String relativePath, ZipOutputStream zos, boolean start) throws IOException { String[] dirList = dir.list(); for (String aDirList : dirList) { File f = new File(dir, aDirList); if (!f.isHidden()) { if (f.isDirectory()) { if (!start) { ZipEntry dirEntry = new ZipEntry(relativePath + f.getName() + "/"); zos.putNextEntry(dirEntry); zos.closeEntry(); } String filePath = f.getPath(); File file = new File(filePath); zipDir(file, relativePath + f.getName() + "/", zos, false); } else { String path = relativePath + f.getName(); if (!path.equals(JarFile.MANIFEST_NAME)) { ZipEntry anEntry = new ZipEntry(path); copyToZipStream(f, anEntry, zos); } } } } }
private List<String> listFromJarFile(JarFile file) { List<String> list = new ArrayList<String>(); for (Enumeration<JarEntry> je = file.entries(); je.hasMoreElements();) { JarEntry entry = je.nextElement(); String s = entry.getName(); if (!s.startsWith(name)) continue; if (!s.endsWith(".class")) continue; s = s.substring(0, s.length() - 6).replace('/', '.'); list.add(s); } return list; }
private void testJarConnectionOn(Resource jar) throws Exception { String toString = jar.getURL().toExternalForm(); // force JarURLConnection String urlString = "jar:" + toString + "!/"; URL newURL = new URL(urlString); System.out.println(newURL); System.out.println(newURL.toExternalForm()); URLConnection con = newURL.openConnection(); System.out.println(con); System.out.println(con instanceof JarURLConnection); JarURLConnection jarCon = (JarURLConnection) con; JarFile jarFile = jarCon.getJarFile(); System.out.println(jarFile.getName()); Enumeration enm = jarFile.entries(); while (enm.hasMoreElements()) System.out.println(enm.nextElement()); }
/** * <p> * Checks the dependencies of the jar file on installed extension. * </p> * @param jarFile containing the attriutes declaring the dependencies */ public static boolean checkExtensionsDependencies(JarFile jar) { if (providers == null) { // no need to bother, nobody is registered to install missing // extensions return true; } try { ExtensionDependency extDep = new ExtensionDependency(); return extDep.checkExtensions(jar); } catch (ExtensionInstallationException e) { debug(e.getMessage()); } return false; }
/** * 返回jar文件所有的目录和文件资源 * 注意jar的open和close * @param jarFile * @return */ public static final List<JarEntry> findJarEntrysByJar(JarFile jarFile) { List<JarEntry> list=new ArrayList<JarEntry>(); if(jarFile==null) { throw new RuntimeException("jarFile is Null"); } Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) {//遍历jar的实体对象 JarEntry jarEntry = jarEntries.nextElement(); list.add(jarEntry); } return list; }
static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception { try (JarFile jf = new JarFile(file)) { JarEntry je = jf.getJarEntry("META-INF/OLD.RSA"); try (InputStream is = jf.getInputStream(je)) { byte[] content = is.readAllBytes(); PKCS7 p7 = new PKCS7(content); SignerInfo[] si = p7.getSignerInfos(); if (si == null || si.length == 0) { throw new Exception("Not signed"); } PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes() .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID); PKCS7 tsToken = new PKCS7((byte[]) p9.getValue()); TimestampToken tt = new TimestampToken(tsToken.getContentInfo().getData()); if (!tt.getHashAlgorithm().toString().equals(digestAlg)) { throw new Exception("Digest alg different"); } if (!tt.getPolicyID().equals(policyId)) { throw new Exception("policyId different"); } } } }
private static String getVersion() { try { String path = VDMJC.class.getName().replaceAll("\\.", "/"); URL url = VDMJC.class.getResource("/" + path + ".class"); JarURLConnection conn = (JarURLConnection)url.openConnection(); JarFile jar = conn.getJarFile(); Manifest mf = jar.getManifest(); String version = (String)mf.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_VERSION); return version; } catch (Exception e) { return null; } }
private static boolean willInstallInSystem (File nbmFile) { boolean res = false; try { JarFile jf = new JarFile (nbmFile); try { for (JarEntry entry : Collections.list (jf.entries ())) { String entryName = entry.getName (); if (entryName.startsWith (NBM_CORE + "/") || entryName.startsWith (NBM_LIB + "/")) { res = true; break; } } } finally { jf.close(); } } catch (IOException ioe) { ERR.log (Level.INFO, ioe.getMessage (), ioe); } return res; }
private Permission getPermission(JarFile jarFile) { try { URLConnection uc = getConnection(jarFile); if (uc != null) return uc.getPermission(); } catch (IOException ioe) { // gulp } return null; }
public ClassIdentifier(JarFile jar, JarIndex index, SidedClassNamer namer, boolean useReferences) { m_index = index; m_namer = namer; m_useReferences = useReferences; m_loader = new TranslatingTypeLoader(jar, index); m_cache = Maps.newHashMap(); }
private void validate(EntityManager em, ImportFileRequest request, File tmpUploadFolder) throws Exception { if (!ServerUtil.isEnoughSpace()) { throw new VmidcException(VmidcMessages.getString("upload.plugin.nospace")); } File[] tmpFolderList = FileUtil.getFileListFromDirectory(tmpUploadFolder.getPath()); for (File tmpFolderFile : tmpFolderList) { String fileName = FilenameUtils.getName(tmpFolderFile.getName()); if (FilenameUtils.getExtension(fileName).equals("bar")) { this.barFile = tmpFolderFile; break; } } if (this.barFile == null) { throw new VmidcBrokerValidationException( "Invalid upload folder. Should contain single .bar file."); } try (JarFile jar = new JarFile(this.barFile)) { Manifest manifest = jar.getManifest(); Attributes attributes = manifest.getMainAttributes(); String symbolicName = attributes.getValue("Deployment-SymbolicName"); if (symbolicName == null) { throw new VmidcBrokerValidationException("uploaded file does not contain Deployment-SymbolicName: " + this.barFile); } this.deploymentName = symbolicName + ".bar"; } }
public void openTemplate() { if (Defaults.getAsBoolean("showTemplateDialog")) { JOptionPane.showMessageDialog(parent, "Each template has some default values for the parameters. " + "Once instantiated you may change them according to your needs."); Defaults.set("showTemplateDialog", "false"); Defaults.save(); } int selectedRow = templateTable.getSelectedRow(); if (selectedRow != -1 && templateTable.getRowCount() != 0) { // close the template panel dialog SwingUtilities.getWindowAncestor(parent).setVisible(false); try { File template = templates[selectedRow].getFile(); File copy = File.createTempFile(template.getName(), ""); FileUtils.copyFile(templates[selectedRow].getFile(), copy); JarFile templateJarFile = new JarFile(copy); // get the path of template Manifest m = templateJarFile.getManifest(); String mainClass = m.getMainAttributes().getValue("Main-Class").toString(); URL url = new URL("file:" + copy.getAbsolutePath()); URLClassLoader myLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader()); Class<?> myClass = myLoader.loadClass(mainClass); // instantiate the template myTemp = (ITemplate) myClass.getConstructor(mediator.getClass()).newInstance(mediator); // shows the input panel of the template myTemp.showDialog(mediator.getMainWindow()); templateJarFile.close(); myLoader.close(); } catch (Exception e) { e.printStackTrace(); } } }
public static boolean extractFromJar(final String fileName, final String dest) throws IOException { if (getRunningJar() == null) { return false; } final File file = new File(dest); if (file.isDirectory()) { file.mkdir(); return false; } if (!file.exists()) { file.getParentFile().mkdirs(); } final JarFile jar = getRunningJar(); final Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { final JarEntry je = e.nextElement(); if (!je.getName().contains(fileName)) { continue; } final InputStream in = new BufferedInputStream(jar.getInputStream(je)); final OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); copyInputStream(in, out); jar.close(); return true; } jar.close(); return false; }
/** * @param packNames 要扫描的包 * @return Set */ public static Set<Class<?>> findFileClass(String... packNames) { Set<Class<?>> clazzs = new LinkedHashSet<Class<?>>(); for (String packName : packNames) { String packageDirName = packName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { //扫描file包中的类 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); getFileClass(packName, filePath, clazzs); } else if ("jar".equals(protocol)) { //扫描jar包中的类 JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile(); getJarClass(jarFile, packageDirName, clazzs); } } } catch (Exception e) { e.getStackTrace(); } } return clazzs; }
public static JarFile getJarFile(){ try{ return new JarFile(SOURCE_LOCATION); }catch(IOException e){ e.printStackTrace(); } return null; }
private static ManifestInfo getManifestInfo() throws IOException { Enumeration<?> resEnum; resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME); while (resEnum.hasMoreElements()) { try { URL url = (URL) resEnum.nextElement(); InputStream is = url.openStream(); if (is != null) { ManifestInfo result = new ManifestInfo(); Manifest manifest = new Manifest(is); Attributes mainAttribs = manifest.getMainAttributes(); result.rsrcMainClass = mainAttribs.getValue(JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME); String rsrcCP = mainAttribs.getValue(JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME); if (rsrcCP == null) rsrcCP = JIJConstants.DEFAULT_REDIRECTED_CLASSPATH; result.rsrcClassPath = splitSpaces(rsrcCP); if ((result.rsrcMainClass != null) && !result.rsrcMainClass.trim().equals("")) //$NON-NLS-1$ return result; } } catch (Exception e) { // Silently ignore wrong manifests on classpath? } } System.err.println( "Missing attributes for JarRsrcLoader in Manifest (" + JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME //$NON-NLS-1$ + ", " + JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME + ")"); //$NON-NLS-1$ //$NON-NLS-2$ return null; }
/** * Unpacks desired folder structure from the JAR file into temporal location and returns that location absolute path * as string. * * @param connection * connection to the JAR file * @param rootName * name of the folder to be unpacked * @return absolute path to the temporarily unpacked folder * @throws IOException * for IO operations */ protected static String recursivelyCopyContent(JarURLConnection connection, String rootName) throws IOException { final File tempFolder = getTempFolder(); tempFolder.deleteOnExit(); final File rootFolder = new File(tempFolder, rootName); if (rootFolder.exists()) { FileDeleter.delete(rootFolder.toPath()); } checkState(rootFolder.mkdir(), "Error while creating folder for Node.js environment. " + rootFolder); checkState(rootFolder.isDirectory(), "Expected directory but got a file: " + rootFolder); rootFolder.deleteOnExit(); try (final JarFile jarFile = connection.getJarFile()) { for (final Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements(); /**/) { final JarEntry entry = em.nextElement(); // Do not process anything which is not under desired root if (!entry.getName().startsWith(rootName)) { continue; } final String fileName = entry.getName();// .substring(connection.getEntryName().length()); final File newResource = new File(tempFolder, fileName); if (entry.isDirectory()) { if (!newResource.exists()) { checkState(newResource.mkdir(), "Error while creating new folder at: " + newResource); } } else { checkState(newResource.createNewFile(), "Error while creating new file at: " + newResource); try (final InputStream is = jarFile.getInputStream(entry)) { com.google.common.io.Files.copy(() -> is, newResource); } } newResource.deleteOnExit(); } } return rootFolder.getCanonicalFile().getAbsolutePath().replace("\\", "\\\\"); }
URLConnection getConnection(JarFile jarFile) throws IOException { URL u; synchronized (instance) { u = urlCache.get(jarFile); } if (u != null) return u.openConnection(); return null; }