/** * Load the policies from the specified file. Also checks that the policies are correctly signed. */ private static void loadPolicies( File jarPathName, CryptoPermissions defaultPolicy, CryptoPermissions exemptPolicy) throws Exception { JarFile jf = new JarFile(jarPathName); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); InputStream is = null; try { if (je.getName().startsWith("default_")) { is = jf.getInputStream(je); defaultPolicy.load(is); } else if (je.getName().startsWith("exempt_")) { is = jf.getInputStream(je); exemptPolicy.load(is); } else { continue; } } finally { if (is != null) { is.close(); } } // Enforce the signer restraint, i.e. signer of JCE framework // jar should also be the signer of the two jurisdiction policy // jar files. JarVerifier.verifyPolicySigned(je.getCertificates()); } // Close and nullify the JarFile reference to help GC. jf.close(); jf = null; }
@Test public void verifySignedJar() throws Exception { String classpath = System.getProperty("java.class.path"); String[] entries = classpath.split(System.getProperty("path.separator")); String signedJarFile = null; for (String entry : entries) { if (entry.contains("bcprov")) { signedJarFile = entry; } } assertThat(signedJarFile).isNotNull(); java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile)); jarFile.getManifest(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); InputStream inputStream = jarFile.getInputStream(jarEntry); inputStream.skip(Long.MAX_VALUE); inputStream.close(); if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() && !jarEntry.getName().endsWith("TigerDigest.class")) { assertThat(jarEntry.getCertificates()).isNotNull(); } } jarFile.close(); }
public void loadOldStylePluginFrom(File pluginFile) throws IOException { JarFile jarFile = new JarFile(pluginFile); // add jar to our extension classLoader SoapUIExtensionClassLoader extensionClassLoader = getExtensionClassLoader(); extensionClassLoader.addFile(pluginFile); // look for factories JarEntry entry = jarFile.getJarEntry("META-INF/factories.xml"); if (entry != null) { getFactoryRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader); } // look for listeners entry = jarFile.getJarEntry("META-INF/listeners.xml"); if (entry != null) { getListenerRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader); } // look for actions entry = jarFile.getJarEntry("META-INF/actions.xml"); if (entry != null) { getActionRegistry().addConfig(jarFile.getInputStream(entry), extensionClassLoader); } // add jar to resource classloader so embedded images can be found with // UISupport.loadImageIcon(..) UISupport.addResourceClassLoader(new URLClassLoader(new URL[] {pluginFile.toURI().toURL()})); }
@SuppressWarnings("resource") public InputStream getInputStream() throws IOException { // 注:JarFile与File的设计是不一样的,File相当于C#的FileInfo,只持有信息, // 而JarFile构造时即打开流,所以每次读取数据时,重新new新的实例,而不作为属性字段持有。 JarFile jarFile = new JarFile(file); return jarFile.getInputStream(jarFile.getEntry(getName())); }
public static void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection) { JarFile jarFile; try { jarFile = jarConnection.getJarFile(); } catch (Exception e) { _.die("Failed to get jar file)"); return; } Enumeration<JarEntry> em = jarFile.entries(); while (em.hasMoreElements()) { JarEntry entry = em.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName()); if (!fileName.equals("/")) { // exclude the directory InputStream entryInputStream = null; try { entryInputStream = jarFile.getInputStream(entry); FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName)); } catch (Exception e) { die("Failed to copy resource: " + fileName); } finally { if (entryInputStream != null) { try { entryInputStream.close(); } catch (Exception e) { } } } } } } }
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; }
/* * (non-Javadoc) * * @see * net.xeoh.plugins.base.impl.classpath.locator.AbstractClassPathLocation * #getInputStream(java.lang.String) */ @Override public InputStream getInputStream(String file) { try { final JarURLConnection connection = (JarURLConnection) new URI("jar:" + this.location + "!/").toURL().openConnection(); final JarFile jarFile = connection.getJarFile(); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); // We only search for class file entries if (entry.isDirectory()) continue; String name = entry.getName(); if (name.equals(file)) return jarFile.getInputStream(entry); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return null; }
public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception { LinkedHashMap entries = new LinkedHashMap(); JarFile jarFileWrapper = null; if (jarFile != null) { logger.debug("Reading jar entries from " + jarFile.getAbsolutePath()); try { jarFileWrapper = new JarFile(jarFile); Enumeration iter = jarFileWrapper.entries(); while (iter.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) iter.nextElement(); InputStream entryStream = jarFileWrapper.getInputStream(zipEntry); ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); try { IOUtils.copy(entryStream, byteArrayStream); entries.put(zipEntry.getName(), byteArrayStream.toByteArray()); logger.debug( "Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath()); } finally { byteArrayStream.close(); } } } finally { if (jarFileWrapper != null) { try { jarFileWrapper.close(); } catch (Exception ignore) { logger.debug(ignore); } } } } return entries; }
private void determineNameMapping(JarFile paramJarFile, Set paramSet, Map paramMap) throws IOException { InputStream localInputStream = paramJarFile.getInputStream(paramJarFile.getEntry("META-INF/INDEX.JD")); if (localInputStream == null) handleException("jardiff.error.noindex", null); LineNumberReader localLineNumberReader = new LineNumberReader(new InputStreamReader(localInputStream, "UTF-8")); String str = localLineNumberReader.readLine(); if ((str == null) || (!str.equals("version 1.0"))) handleException("jardiff.error.badheader", str); while ((str = localLineNumberReader.readLine()) != null) { List localList; if (str.startsWith("remove")) { localList = getSubpaths(str.substring("remove".length())); if (localList.size() != 1) handleException("jardiff.error.badremove", str); paramSet.add(localList.get(0)); continue; } if (str.startsWith("move")) { localList = getSubpaths(str.substring("move".length())); if (localList.size() != 2) handleException("jardiff.error.badmove", str); if (paramMap.put(localList.get(1), localList.get(0)) != null) handleException("jardiff.error.badmove", str); continue; } if (str.length() <= 0) continue; handleException("jardiff.error.badcommand", str); } localLineNumberReader.close(); localInputStream.close(); }
private static String getVersionFromPomProperties(File artifact) throws IOException { List<JarEntry> pomPropertiesFiles = new ArrayList<>(); String versionNumber = null; try (JarFile jar = new JarFile(artifact)) { JarEntry entry; Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { entry = entries.nextElement(); if (!entry.isDirectory() && entry.getName().endsWith("pom.properties")) { pomPropertiesFiles.add(entry); } } if (pomPropertiesFiles.size() == 1) { Properties pomProperties = new Properties(); pomProperties.load(jar.getInputStream(pomPropertiesFiles.get(0))); versionNumber = pomProperties.getProperty("version", null); } else { logger.debug( "Found {} pom.properties files. Cannot use that for version", pomPropertiesFiles.size()); } } return versionNumber; }
public byte[] read(String path) throws IOException { ZipEntry entry = m_source.getEntry(getInternalPath(path)); if (entry == null) { throw new IOException("Jar Entry is not found for class " + path + "."); } return Streams.readBytes(m_source.getInputStream(entry)); }
@SuppressWarnings("unchecked") private static void startPlugins() { logger.info("Loading available plugins"); final Collection<File> botJars = FileUtils.listFiles(pluginsDirecotry, new String[] {"jar"}, false); for (File botJar : botJars) { try { JarFile jar = new JarFile(botJar); ZipEntry ze = jar.getEntry("plugin.yml"); if (ze == null) throw new RuntimeException("Plugin has no plugin.yml file!"); InputStream is = jar.getInputStream(ze); YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true); String mainClass = n.getString("mainClass"); String name = n.getString("name"); URLClassLoader loader = new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader()); Plugin plugin = loader.loadClass(mainClass).asSubclass(Plugin.class).newInstance(); plugin.start(); PLUGIN_INFO.put(name, new PluginInfo(name, plugin, n)); logger.info("Loaded plugin '{}'", name); } catch (Exception e) { logger.error("Failed to load plugin from {}", botJar.getName()); e.printStackTrace(); } } logger.info("Loaded {} plugin(s)", PLUGIN_INFO.size()); }
public static void extractFileFromJar(String archive, List<String> filenames, String destination) throws IOException { // open the jar (zip) file JarFile jar = new JarFile(archive); // parse the entries Enumeration<JarEntry> entryEnum = jar.entries(); while (entryEnum.hasMoreElements()) { JarEntry file = entryEnum.nextElement(); if (filenames.contains(file.getName())) { // match found File f = new File(destination + File.separator + file.getName()); InputStream in = jar.getInputStream(file); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f)); byte[] byteBuffer = new byte[1024]; int numRead; while ((numRead = in.read(byteBuffer)) != -1) { out.write(byteBuffer, 0, numRead); } in.close(); out.close(); } } jar.close(); }
@SuppressWarnings("unchecked") private static void loadBots() { logger.info("Loading available bots"); final Collection<File> botJars = FileUtils.listFiles(botsDirecotry, new String[] {"jar"}, false); for (File botJar : botJars) { try { JarFile jar = new JarFile(botJar); ZipEntry entry = jar.getEntry("bot.yml"); if (entry == null) throw new RuntimeException("Bot has no bot.yml file!"); InputStream is = jar.getInputStream(entry); YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true); String mainClass = n.getString("mainClass"); String type = n.getString("type"); URLClassLoader loader = new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader()); BOT_INFO.put(type, new BotClassInfo(loader.loadClass(mainClass).asSubclass(Bot.class), n)); logger.info("Loaded bot '{}'", type); } catch (Exception e) { logger.error("Failed to load bot from {}", botJar.getName()); e.printStackTrace(); } } logger.info("Loaded {} bot(s)", BOT_INFO.size()); }
public static boolean copyJarResourcesRecursively( final File destDir, final JarURLConnection jarConnection) throws IOException { final JarFile jarFile = jarConnection.getJarFile(); for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) { final JarEntry entry = e.nextElement(); if (entry.getName().startsWith(jarConnection.getEntryName())) { final String filename = entry.getName(); final File f = new File(destDir, filename); if (!entry.isDirectory()) { final InputStream entryInputStream = jarFile.getInputStream(entry); if (!FileUtils.copyStream(entryInputStream, f)) { return false; } entryInputStream.close(); } else { if (!FileUtils.ensureDirectoryExists(f)) { throw new IOException("Could not create directory: " + f.getAbsolutePath()); } } } } return true; }
/** Check the certificates with the ones in the jar file (all must match). */ private static final void validateCertificate( final Certificate[] rootCerts, final JarFile jar, final JarEntry entry, final byte[] buf) throws IOException, SecurityException { if (DEBUG) { System.err.println("JarUtil: validate JarEntry : " + entry.getName()); } // API states that we must read all of the data from the entry's // InputStream in order to be able to get its certificates final InputStream is = jar.getInputStream(entry); try { while (is.read(buf) > 0) {} } finally { is.close(); } // Get the certificates for the JAR entry final Certificate[] nativeCerts = entry.getCertificates(); if (nativeCerts == null || nativeCerts.length == 0) { throw new SecurityException("no certificate for " + entry.getName() + " in " + jar.getName()); } if (!SecurityUtil.equals(rootCerts, nativeCerts)) { throw new SecurityException( "certificates not equal for " + entry.getName() + " in " + jar.getName()); } }
public static void unjar(File dest, String jar) throws IOException { dest.mkdirs(); JarFile jf = new JarFile(jar); try { Enumeration es = jf.entries(); while (es.hasMoreElements()) { JarEntry je = (JarEntry) es.nextElement(); String n = je.getName(); File f = new File(dest, n); if (je.isDirectory()) { f.mkdirs(); } else { if (f.exists()) { f.delete(); } else { f.getParentFile().mkdirs(); } InputStream is = jf.getInputStream(je); FileOutputStream os = new FileOutputStream(f); try { copyStream(is, os); } finally { os.close(); } } long time = je.getTime(); if (time != -1) f.setLastModified(time); } } finally { jf.close(); } }
public static DeviceEntry getDevice(String device) { try { if (props.containsKey(device)) return (DeviceEntry) props.get(device); else { File f = new File( OS.getWorkDir() + File.separator + "devices" + File.separator + device + ".ftd"); if (f.exists()) { DeviceEntry ent = null; JarFile jar = new JarFile(f); Enumeration e = jar.entries(); while (e.hasMoreElements()) { JarEntry file = (JarEntry) e.nextElement(); if (file.getName().endsWith(device + ".properties")) { InputStream is = jar.getInputStream(file); // get the input stream PropertiesFile p = new PropertiesFile(); p.load(is); ent = new DeviceEntry(p); } } return ent; } else return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } }
private LameResult index(JarFile jar, JarEntry jarEntry) throws IOException, MojoExecutionException { // lib/spring.jar // suffix -> ".jar // prefix -> "spring" String name = jarEntry.getName(); int dotIndex = name.lastIndexOf('.'); String suffix = name.substring(dotIndex); int slashIndex = name.lastIndexOf('/'); String prefix; if (slashIndex == -1) { prefix = name.substring(0, dotIndex); } else { prefix = name.substring(slashIndex + 1, dotIndex); } Path tempPath = Files.createTempFile(prefix, suffix); File tempFile = tempPath.toFile(); try (InputStream input = jar.getInputStream(jarEntry)) { // Files.copy will do the buffering Files.copy(input, tempPath, REPLACE_EXISTING); } LameIndex lameIndex; try (JarFile tempJar = new JarFile(tempFile)) { lameIndex = index(tempJar); } boolean changed = lameIndex.changed; if (changed) { tempFile = writeIndexes(tempFile, name, lameIndex.subDeploymentIndices); return new LameResult(tempFile, true, lameIndex.index); } else { return new LameResult(null, false, null); } }
public static void copyJarContents(String prefix, String pathToJar) throws IOException { LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix); JarFile jar = null; 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(); }
/** * 通过流将jar中的一个文件的内容输出 * * @param jarPaht jar文件存放的位置 * @param filePaht 指定的文件目录 */ private void getStream(String jarPath, String filePath) { JarFile jarFile = null; try { jarFile = new JarFile(jarPath); } catch (IOException e1) { e1.printStackTrace(); } Enumeration<JarEntry> ee = jarFile.entries(); List<JarEntry> jarEntryList = new ArrayList<JarEntry>(); while (ee.hasMoreElements()) { JarEntry entry = ee.nextElement(); // 过滤我们出满足我们需求的东西,这里的fileName是指向一个具体的文件的对象的完整包路径,比如com/mypackage/test.txt if (entry.getName().startsWith(filePath)) { jarEntryList.add(entry); } } try { InputStream in = jarFile.getInputStream(jarEntryList.get(0)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = ""; while ((s = br.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } }
private Class<?> loadClassFromJar(String className) throws ClassNotFoundException { Class<?> result = null; result = classes.get(className); // checks in cached classes if (result != null) { return result; } try { final JarFile jar = new JarFile(jarFile); try { final String path = className.replace('.', '/'); final JarEntry entry = jar.getJarEntry(path + ".class"); final InputStream in = jar.getInputStream(entry); try { final byte[] classBytes = IOUtils.toByteArray(in); result = defineClass(className, classBytes, 0, classBytes.length, null); classes.put(className, result); return result; } finally { in.close(); } } finally { jar.close(); } } catch (Exception e) { throw new ClassNotFoundException("Can't find class " + className + " in jar " + jarFile, e); } }
private static void copyFiles(Manifest manifest, JarFile in, JarOutputStream out, long timestamp) throws IOException { byte[] buffer = new byte[4096]; int num; Map<String, Attributes> entries = manifest.getEntries(); List<String> names = new ArrayList<String>(entries.keySet()); Collections.sort(names); for (String name : names) { JarEntry inEntry = in.getJarEntry(name); JarEntry outEntry = null; if (inEntry.getMethod() == ZipEntry.STORED) { outEntry = new JarEntry(inEntry); } else { outEntry = new JarEntry(name); } outEntry.setTime(timestamp); out.putNextEntry(outEntry); InputStream data = in.getInputStream(inEntry); while ((num = data.read(buffer)) > 0) { out.write(buffer, 0, num); } out.flush(); } }
public void connect() throws IOException { if (!connected) { String path = url.getPath(); Matcher matcher = urlPattern.matcher(path); if (matcher.matches()) { path = matcher.group(1); String subPath = matcher.group(2); JarURLConnection jarURLConnection = (JarURLConnection) new URL("jar:" + path).openConnection(); inputStream = jarURLConnection.getInputStream(); if (subPath.isEmpty() == false) { JarFile jar = retrieve(new URL(path), inputStream); String[] nodes = nestingSeparatorPattern.split(subPath); int i; for (i = 0; i < nodes.length - 1; i++) { path += "!/" + nodes[i]; jar = retrieve(new URL(path), inputStream); } ZipEntry entry = jar.getEntry(nodes[i]); entrySize = entry.getSize(); inputStream = jar.getInputStream(entry); } } else { throw new MalformedURLException("Invalid JAP URL path: " + path); } connected = true; } }
/** * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file. * * @param f The jar file to extract from. * @return a temporary file to which the plugin.xml file has been copied. */ public static File unpackPluginXML(File f) { InputStream in = null; OutputStream out = null; try { JarFile jar = new JarFile(f); ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE); if (entry == null) { return null; } File dest = File.createTempFile("jabref_plugin", ".xml"); dest.deleteOnExit(); in = new BufferedInputStream(jar.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[2048]; for (; ; ) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); return dest; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
@RequestMapping("/source") public void source( Model model, @RequestParam("id") String jarid, @RequestParam("clz") String clazzName, @RequestParam(value = "type", required = false, defaultValue = "asmdump") String type) { model.addAttribute("clzName", clazzName); model.addAttribute("id", jarid); if (Database.get(jarid) == null) { return; } FileItem path = (FileItem) Database.get(jarid).getObj(); model.addAttribute("jarFile", path); try { JarFile jarFile = new JarFile(path.getFullName()); String code = ""; JarEntry entry = jarFile.getJarEntry(clazzName); InputStream inputStream = jarFile.getInputStream(entry); if (type.equals("asmdump")) { code = asmDump(inputStream); } else if (type.equals("decomp")) { code = jclazzDecomp(clazzName, inputStream); } model.addAttribute("code", code); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Unpacks a jar file to a temporary directory that will be removed when the VM exits. * * @param jarfilePath the path of the jar to unpack * @return the path of the temporary directory */ private static String explodeJarToTempDir(File jarfilePath) { try { final Path jarfileDir = Files.createTempDirectory(jarfilePath.getName()); Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { delete(jarfileDir.toFile()); } }); jarfileDir.toFile().deleteOnExit(); JarFile jarfile = new JarFile(jarfilePath); Enumeration<JarEntry> entries = jarfile.entries(); while (entries.hasMoreElements()) { JarEntry e = entries.nextElement(); if (!e.isDirectory()) { File path = new File(jarfileDir.toFile(), e.getName().replace('/', File.separatorChar)); File dir = path.getParentFile(); dir.mkdirs(); assert dir.exists(); Files.copy(jarfile.getInputStream(e), path.toPath()); } } return jarfileDir.toFile().getAbsolutePath(); } catch (IOException e) { throw new AssertionError(e); } }
/** * Gets the manifest. * * @param jarName the jar name * @param lineSeparator the line separator * @return the manifest */ public String getManifest(final String jarName, final String lineSeparator) { StringBuilder sb = new StringBuilder(); String lib = getLibraryPathName(jarBaseName); if (!isEmpty(lib)) { lib = lib.replaceAll("file:", ""); final File[] files = new File(lib).listFiles(new FilenameFilterJar()); if ((files != null) && (files.length > 0)) { for (File jar : files) { if (jar.getName().matches(".*" + jarName + ".*") && jar.exists()) { try { JarFile jarFile = new JarFile(jar); final JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF"); final InputStream is = jarFile.getInputStream(entry); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { sb.append(lineSeparator).append(line); } if (jarFile != null) { jarFile.close(); jarFile = null; } } catch (final Exception e) { } } } } } return sb.toString(); }
/** * Removes an entry from a jar file * * @param jar The jar file * @param entryName The name of the entry to remove * @return The data of the jar with the entry removed * @throws IOException */ public static byte[] removeJarEntry(JarFile jar, String entryName) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JarOutputStream jarOut = new JarOutputStream(bytes); // copy all entries except the one with the matching name Set<String> copiedEntries = new HashSet<String>(); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = jarEntries.nextElement(); String name = entry.getName(); if (!name.equals(entryName)) { if (!copiedEntries.contains(name)) { jarOut.putNextEntry(entry); InputStream entryStream = jar.getInputStream(entry); byte[] entryBytes = streamToBytes(entryStream); entryStream.close(); jarOut.write(entryBytes); jarOut.closeEntry(); copiedEntries.add(name); } } } jarOut.flush(); jarOut.close(); return bytes.toByteArray(); }
/** Copies all entries under the path specified by the jarPath to the JarOutputStream. */ private void copyJarEntries(URL jarPath, Set<String> entries, JarOutputStream jarOut) throws IOException { String spec = new URL(jarPath.getFile()).getFile(); String entryRoot = spec.substring(spec.lastIndexOf('!') + 1); if (entryRoot.charAt(0) == '/') { entryRoot = entryRoot.substring(1); } JarFile jarFile = new JarFile(spec.substring(0, spec.lastIndexOf('!'))); try { Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String name = jarEntry.getName(); if (name == null || !name.startsWith(entryRoot)) { continue; } if (entries.add(name)) { jarOut.putNextEntry(new JarEntry(jarEntry)); ByteStreams.copy(jarFile.getInputStream(jarEntry), jarOut); jarOut.closeEntry(); } } } finally { jarFile.close(); } }