List of usage examples for java.util.jar JarInputStream close
public void close() throws IOException
From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java
/** * Returns a file from a jar as a byte array. * * @param file the jar file//from www . j a v a 2 s . com * @param name the entry name * @return the file content * @throws IOException for any I/O error */ private byte[] getEntry(File file, String name) throws IOException { JarInputStream stream = new JarInputStream(new FileInputStream(file)); try { JarEntry entry; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); while ((entry = stream.getNextJarEntry()) != null) { if (entry.getName().endsWith(name)) { IOUtils.copy(stream, bytes); return bytes.toByteArray(); } } fail("Entry not found: " + name); } finally { stream.close(); } return null; }
From source file:fll.xml.XMLUtils.java
/** * Get all challenge descriptors build into the software. *///from ww w. j av a2s .co m public static Collection<URL> getAllKnownChallengeDescriptorURLs() { final String baseDir = "fll/resources/challenge-descriptors/"; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final URL directory = classLoader.getResource(baseDir); if (null == directory) { LOGGER.warn("base dir for challenge descriptors not found"); return Collections.emptyList(); } final Collection<URL> urls = new LinkedList<URL>(); if ("file".equals(directory.getProtocol())) { try { final URI uri = directory.toURI(); final File fileDir = new File(uri); final File[] files = fileDir.listFiles(); if (null != files) { for (final File file : files) { if (file.getName().endsWith(".xml")) { try { final URL fileUrl = file.toURI().toURL(); urls.add(fileUrl); } catch (final MalformedURLException e) { LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e); } } } } } catch (final URISyntaxException e) { LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e); } } else if (directory.getProtocol().equals("jar")) { final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource(); if (null != src) { final URL jar = src.getLocation(); JarInputStream zip = null; try { zip = new JarInputStream(jar.openStream()); JarEntry ze = null; while ((ze = zip.getNextJarEntry()) != null) { final String entryName = ze.getName(); if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) { // add 1 to baseDir to skip past the path separator final String challengeName = entryName.substring(baseDir.length()); // check that the file really exists and turn it into a URL final URL challengeUrl = classLoader.getResource(baseDir + challengeName); if (null != challengeUrl) { urls.add(challengeUrl); } else { // TODO could write the resource out to a temporary file if // needed // then mark the file as delete on exit LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: " + entryName); } } } zip.close(); } catch (final IOException e) { LOGGER.error("Error reading jar file at: " + jar.toString(), e); } finally { IOUtils.closeQuietly(zip); } } else { LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors"); } } else { throw new UnsupportedOperationException("Cannot list files for URL " + directory); } return urls; }
From source file:org.bimserver.plugins.classloaders.FileJarClassLoader.java
private void loadEmbeddedJarFileSystems(Path path) { try {/*from w w w . j a v a2s . c o m*/ if (Files.isDirectory(path)) { for (Path subPath : PathUtils.list(path)) { loadEmbeddedJarFileSystems(subPath); } } else { // This is annoying, but we are caching the contents of JAR files within JAR files in memory, could not get the JarFileSystem to work with jar:jar:file URI's // Also there is a problem with not being able to change position within a file, at least in the JarFileSystem // It looks like there are 2 other solutions to this problem: // - Copy the embedded JAR files to a tmp directory, and load from there with a JarFileSystem wrapper (at some stage we were doing this for all JAR contents, // resulted in 50.000 files, which was annoying, but a few JAR files probably won't hurt // - Don't allow plugins to have embedded JAR's, could force them to extract all dependencies... // if (path.getFileName().toString().toLowerCase().endsWith(".jar")) { JarInputStream jarInputStream = new JarInputStream(Files.newInputStream(path)); try { JarEntry jarEntry = jarInputStream.getNextJarEntry(); while (jarEntry != null) { jarContent.put(jarEntry.getName(), IOUtils.toByteArray(jarInputStream)); jarEntry = jarInputStream.getNextJarEntry(); } } finally { jarInputStream.close(); } } } } catch (IOException e) { LOGGER.error("", e); } }
From source file:com.speed.ob.api.ClassStore.java
public void dump(File in, File out, Config config) throws IOException { if (in.isDirectory()) { for (ClassNode node : nodes()) { String[] parts = node.name.split("\\."); String dirName = node.name.substring(0, node.name.lastIndexOf(".")); dirName = dirName.replace(".", "/"); File dir = new File(out, dirName); if (!dir.exists()) { if (!dir.mkdirs()) throw new IOException("Could not make output dir: " + dir.getAbsolutePath()); }/*from w w w . j a v a 2 s . c om*/ ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); FileOutputStream fOut = new FileOutputStream( new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1))); fOut.write(data); fOut.flush(); fOut.close(); } } else if (in.getName().endsWith(".jar")) { File output = new File(out, in.getName()); JarFile jf = new JarFile(in); HashMap<JarEntry, Object> existingData = new HashMap<>(); if (output.exists()) { try { JarInputStream jarIn = new JarInputStream(new FileInputStream(output)); JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if (!entry.isDirectory()) { byte[] data = IOUtils.toByteArray(jarIn); existingData.put(entry, data); jarIn.closeEntry(); } } jarIn.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Could not read existing output file, overwriting", e); } } FileOutputStream fout = new FileOutputStream(output); Manifest manifest = null; if (jf.getManifest() != null) { manifest = jf.getManifest(); if (!config.getBoolean("ClassNameTransform.keep_packages") && config.getBoolean("ClassNameTransform.exclude_mains")) { manifest = new Manifest(manifest); if (manifest.getMainAttributes().getValue("Main-Class") != null) { String manifestName = manifest.getMainAttributes().getValue("Main-Class"); if (manifestName.contains(".")) { manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1); manifest.getMainAttributes().putValue("Main-Class", manifestName); } } } } jf.close(); JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout) : new JarOutputStream(fout, manifest); Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files"); if (!existingData.isEmpty()) { for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) { Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName()); jarOut.putNextEntry(entry.getKey()); jarOut.write((byte[]) entry.getValue()); jarOut.closeEntry(); } } for (ClassNode node : nodes()) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); int index = node.name.lastIndexOf("/"); String fileName; if (index > 0) { fileName = node.name.substring(0, index + 1).replace(".", "/"); fileName += node.name.substring(index + 1).concat(".class"); } else { fileName = node.name.concat(".class"); } JarEntry entry = new JarEntry(fileName); jarOut.putNextEntry(entry); jarOut.write(data); jarOut.closeEntry(); } jarOut.close(); } else { if (nodes().size() == 1) { File outputFile = new File(out, in.getName()); ClassNode node = nodes().iterator().next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); byte[] data = writer.toByteArray(); FileOutputStream stream = new FileOutputStream(outputFile); stream.write(data); stream.close(); } } }
From source file:com.dragome.callbackevictor.serverside.utils.RewritingUtils.java
public static boolean rewriteJar(final JarInputStream pInput, final ResourceTransformer transformer, final JarOutputStream pOutput, final Matcher pMatcher) throws IOException { boolean changed = false; while (true) { final JarEntry entry = pInput.getNextJarEntry(); if (entry == null) { break; }//from ww w . j ava 2s. c o m if (entry.isDirectory()) { pOutput.putNextEntry(new JarEntry(entry)); continue; } final String name = entry.getName(); pOutput.putNextEntry(new JarEntry(name)); if (name.endsWith(".class")) { if (pMatcher.isMatching(name)) { if (log.isDebugEnabled()) { log.debug("transforming " + name); } final byte[] original = toByteArray(pInput); byte[] transformed = transformer.transform(original); pOutput.write(transformed); changed |= transformed.length != original.length; continue; } } else if (name.endsWith(".jar") || name.endsWith(".ear") || name.endsWith(".zip") || name.endsWith(".war")) { changed |= rewriteJar(new JarInputStream(pInput), transformer, new JarOutputStream(pOutput), pMatcher); continue; } int length = copy(pInput, pOutput); log.debug("copied " + name + "(" + length + ")"); } pInput.close(); pOutput.close(); return changed; }
From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java
/** * Loads a plugin descriptor from the given plugin jar and returns it. * * This is a static method to provide a convenience method for others to be able to use. * * @param pluginJarFileUrl URL to a plugin jar file * @return the plugin descriptor found in the given plugin jar file * @throws PluginContainerException if failed to find or parse a descriptor file in the plugin jar *//*from w w w.j a va2 s. c om*/ public static PluginDescriptor loadPluginDescriptorFromUrl(URL pluginJarFileUrl) throws PluginContainerException { final Log logger = LogFactory.getLog(AgentPluginDescriptorUtil.class); if (pluginJarFileUrl == null) { throw new PluginContainerException("A valid plugin JAR URL must be supplied."); } logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]..."); testPluginJarIsReadable(pluginJarFileUrl); JarInputStream jis = null; JarEntry descriptorEntry = null; ValidationEventCollector validationEventCollector = new ValidationEventCollector(); try { jis = new JarInputStream(pluginJarFileUrl.openStream()); JarEntry nextEntry = jis.getNextJarEntry(); while (nextEntry != null && descriptorEntry == null) { if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) { descriptorEntry = nextEntry; } else { jis.closeEntry(); nextEntry = jis.getNextJarEntry(); } } if (descriptorEntry == null) { throw new Exception("The plugin descriptor does not exist"); } return parsePluginDescriptor(jis, validationEventCollector); } catch (Exception e) { throw new PluginContainerException( "Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH + "] found in plugin jar at [" + pluginJarFileUrl + "].", new WrappedRemotingException(e)); } finally { if (jis != null) { try { jis.close(); } catch (Exception e) { logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e); } } logValidationEvents(pluginJarFileUrl, validationEventCollector, logger); } }
From source file:ezbake.frack.submitter.util.JarUtilTest.java
@Test public void addFileToJar() throws IOException { File tmpDir = new File("jarUtilTest"); try {/*from w w w . ja va2 s . c o m*/ tmpDir.mkdirs(); // Push the example jar to a file byte[] testJar = IOUtils.toByteArray(this.getClass().getResourceAsStream("/example.jar")); File jarFile = new File(tmpDir, "example.jar"); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(jarFile)); os.write(testJar); os.close(); // Push the test content to a file byte[] testContent = IOUtils.toByteArray(this.getClass().getResourceAsStream("/test.txt")); String stringTestContent = new String(testContent); File testFile = new File(tmpDir, "test.txt"); os = new BufferedOutputStream(new FileOutputStream(testFile)); os.write(testContent); os.close(); assertTrue(jarFile.exists()); assertTrue(testFile.exists()); // Add the new file to the jar File newJar = JarUtil.addFilesToJar(jarFile, Lists.newArrayList(testFile)); assertTrue("New jar file exists", newJar.exists()); assertTrue("New jar is a file", newJar.isFile()); // Roll through the entries of the new jar and JarInputStream is = new JarInputStream(new FileInputStream(newJar)); JarEntry entry = is.getNextJarEntry(); boolean foundNewFile = false; String content = ""; while (entry != null) { String name = entry.getName(); if (name.endsWith("test.txt")) { foundNewFile = true; byte[] buffer = new byte[1]; while ((is.read(buffer)) > 0) { content += new String(buffer); } break; } entry = is.getNextJarEntry(); } is.close(); assertTrue("New file was in repackaged jar", foundNewFile); assertEquals("Content of added file is the same as the retrieved new file", stringTestContent, content); } finally { FileUtils.deleteDirectory(tmpDir); } }
From source file:org.apache.openjpa.eclipse.PluginLibrary.java
void copyJar(JarInputStream jar, JarOutputStream out) throws IOException { if (jar == null || out == null) return;// ww w. j a va2s . c om try { JarEntry entry = null; while ((entry = jar.getNextJarEntry()) != null) { out.putNextEntry(entry); int b = -1; while ((b = jar.read()) != -1) { out.write(b); } } out.closeEntry(); } finally { out.finish(); out.flush(); out.close(); jar.close(); } }
From source file:com.geewhiz.pacify.TestArchive.java
@Test public void checkJarWhereTheSourceIsntAJarPerDefinition() throws ArchiveException, IOException { LoggingUtils.setLogLevel(logger, Level.ERROR); String testFolder = "testArchive/correct/jarWhereSourceIsntAJarPerDefinition"; File testResourceFolder = new File("src/test/resources/", testFolder); File targetResourceFolder = new File("target/test-resources/", testFolder); LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder, createPropertyResolveManager(propertiesToUseWhileResolving)); Assert.assertEquals("We shouldnt get any defects.", 0, defects.size()); JarInputStream in = new JarInputStream( new FileInputStream(new File(testResourceFolder, "package/archive.jar"))); JarInputStream out = new JarInputStream( new FileInputStream(new File(targetResourceFolder, "package/archive.jar"))); Assert.assertNull("SRC jar should be a jar which is packed via zip, so the first entry isn't the manifest.", in.getManifest());/*from w w w .j a va2 s .co m*/ Assert.assertNotNull("RESULT jar should contain the manifest as first entry", out.getManifest()); in.close(); out.close(); checkIfResultIsAsExpected(testFolder); }
From source file:org.bimserver.plugins.JarClassLoader.java
public JarClassLoader(ClassLoader parentClassLoader, File jarFile) { super(parentClassLoader); this.jarFile = jarFile; try {//from w ww .ja v a 2s. c om JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry entry = jarInputStream.getNextJarEntry(); map = new HashMap<String, byte[]>(); while (entry != null) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarInputStream, byteArrayOutputStream); map.put(entry.getName(), byteArrayOutputStream.toByteArray()); if (entry.getName().endsWith(".jar")) { loadSubJars(byteArrayOutputStream.toByteArray()); } entry = jarInputStream.getNextJarEntry(); } jarInputStream.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } }