List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:org.apache.maven.plugins.shade.resource.ServiceResourceTransformerTest.java
@Test public void concatenation() throws Exception { SimpleRelocator relocator = new SimpleRelocator("org.foo", "borg.foo", null, null); List<Relocator> relocators = Lists.<Relocator>newArrayList(relocator); String content = "org.foo.Service\n"; byte[] contentBytes = content.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentResource = "META-INF/services/org.something.another"; ServicesResourceTransformer xformer = new ServicesResourceTransformer(); xformer.processResource(contentResource, contentStream, relocators); contentStream.close();/*from www . j a va2 s. c o m*/ content = "org.blah.Service\n"; contentBytes = content.getBytes("UTF-8"); contentStream = new ByteArrayInputStream(contentBytes); contentResource = "META-INF/services/org.something.another"; xformer.processResource(contentResource, contentStream, relocators); contentStream.close(); 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(contentResource); assertNotNull(jarEntry); InputStream entryStream = jarFile.getInputStream(jarEntry); try { String xformedContent = IOUtils.toString(entryStream, "utf-8"); // must be two lines, with our two classes. String[] classes = xformedContent.split("\r?\n"); boolean h1 = false; boolean h2 = false; for (String name : classes) { if ("org.blah.Service".equals(name)) { h1 = true; } else if ("borg.foo.Service".equals(name)) { h2 = true; } } assertTrue(h1 && h2); } finally { IOUtils.closeQuietly(entryStream); jarFile.close(); } } finally { if (jos != null) { IOUtils.closeQuietly(jos); } tempJar.delete(); } }
From source file:com.android.builder.testing.MockableJarGenerator.java
public void createMockableJar(File input, File output) throws IOException { Preconditions.checkState(output.createNewFile(), "Output file [%s] already exists.", output.getAbsolutePath());/*from www . j a va 2 s .c o m*/ JarFile androidJar = null; JarOutputStream outputStream = null; try { androidJar = new JarFile(input); outputStream = new JarOutputStream(new FileOutputStream(output)); for (JarEntry entry : Collections.list(androidJar.entries())) { InputStream inputStream = androidJar.getInputStream(entry); if (entry.getName().endsWith(".class")) { if (!skipClass(entry.getName().replace("/", "."))) { rewriteClass(entry, inputStream, outputStream); } } else { outputStream.putNextEntry(entry); ByteStreams.copy(inputStream, outputStream); } inputStream.close(); } } finally { if (androidJar != null) { androidJar.close(); } if (outputStream != null) { outputStream.close(); } } }
From source file:org.hyperic.hq.plugin.activemq.EmbeddedActiveMQServerDetector.java
@Override protected File findVersionFile(File dir, Pattern pattern) { File res = null;/*from ww w . j av a 2 s . co m*/ log.debug("[findVersionFile] dir=" + dir + " pattern=" + pattern); if (!dir.exists()) { log.debug("File '" + dir + "' Not Found"); return null; } // In an Embedded ActiveMQ instance, we know we are starting with // CATALINA_BASE // Give preferential search treatment to webapps/*/WEB-INF/lib for // performance gains File libDir = new File(dir, "lib"); if (libDir.exists()) { File versionFile = super.findVersionFile(libDir, pattern); if (versionFile != null) { res = versionFile; } } if (res == null) { File webappsDir = new File(dir, "webapps"); if (webappsDir.exists()) { for (File app : webappsDir.listFiles()) { if (app.isDirectory()) { File wlibDir = new File(app, "WEB-INF" + File.separator + "lib"); if (wlibDir.exists()) { File versionFile = super.findVersionFile(wlibDir, pattern); if (versionFile != null) { res = versionFile; } } } else if (app.getName().endsWith(".war")) { JarFile war = null; try { war = new JarFile(app); Enumeration<JarEntry> files = war.entries(); while (files.hasMoreElements()) { final String fileName = files.nextElement().toString(); if (pattern.matcher(fileName).find()) { res = new File(app + "!" + fileName); break; } } } catch (IOException ex) { log.debug("Error: '" + app + "': " + ex.getMessage(), ex); } finally { if (war != null) { try { war.close(); } catch (IOException e) { log.debug("Unable to close war file: " + e.getMessage(), e); } } } } } } } if ((res == null) && recursive) { res = super.findVersionFile(dir, pattern); } log.debug("[findVersionFile] res=" + res); return res; }
From source file:org.apache.hadoop.hbase.util.CoprocessorClassLoader.java
private void init(Path path, String pathPrefix, Configuration conf) throws IOException { // Copy the jar to the local filesystem String parentDirStr = conf.get(LOCAL_DIR_KEY, DEFAULT_LOCAL_DIR) + TMP_JARS_DIR; synchronized (parentDirLockSet) { if (!parentDirLockSet.contains(parentDirStr)) { Path parentDir = new Path(parentDirStr); FileSystem fs = FileSystem.getLocal(conf); fs.delete(parentDir, true); // it's ok if the dir doesn't exist now parentDirLockSet.add(parentDirStr); if (!fs.mkdirs(parentDir) && !fs.getFileStatus(parentDir).isDirectory()) { throw new RuntimeException("Failed to create local dir " + parentDirStr + ", CoprocessorClassLoader failed to init"); }/*ww w . j av a 2 s . c o m*/ } } FileSystem fs = path.getFileSystem(conf); File dst = new File(parentDirStr, "." + pathPrefix + "." + path.getName() + "." + System.currentTimeMillis() + ".jar"); fs.copyToLocalFile(path, new Path(dst.toString())); dst.deleteOnExit(); addURL(dst.getCanonicalFile().toURI().toURL()); JarFile jarFile = new JarFile(dst.toString()); try { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); Matcher m = libJarPattern.matcher(entry.getName()); if (m.matches()) { File file = new File(parentDirStr, "." + pathPrefix + "." + path.getName() + "." + System.currentTimeMillis() + "." + m.group(1)); IOUtils.copyBytes(jarFile.getInputStream(entry), new FileOutputStream(file), conf, true); file.deleteOnExit(); addURL(file.toURI().toURL()); } } } finally { jarFile.close(); } }
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException { JarFile jarFile = new JarFile(jar); JarEntry entry = jarFile.getJarEntry(pathName); InputStream input = jarFile.getInputStream(entry); byte[] classData = new byte[(int) entry.getSize()]; int totalBytes = 0; while (totalBytes < classData.length) { int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes); if (bytesRead == -1) { throw new IOException("Jar Entry too short!"); }/*ww w. j a v a2 s .c om*/ totalBytes += bytesRead; } Class<?> loadedClass = defineClass(name, classData, 0, classData.length, new CodeSource(url, entry.getCertificates())); input.close(); jarFile.close(); return loadedClass; }
From source file:de.nmichael.efa.Daten.java
public static Vector getEfaInfos(boolean efaInfos, boolean pluginInfos, boolean javaInfos, boolean hostInfos, boolean jarInfos) { Vector infos = new Vector(); // efa-Infos//from w w w . ja va2 s. c o m if (efaInfos) { infos.add("efa.version=" + Daten.VERSIONID); if (EFALIVE_VERSION != null && EFALIVE_VERSION.length() > 0) { infos.add("efalive.version=" + Daten.EFALIVE_VERSION); } if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { if (Daten.efaMainDirectory != null) { infos.add("efa.dir.main=" + Daten.efaMainDirectory); } if (Daten.efaBaseConfig != null && Daten.efaBaseConfig.efaUserDirectory != null) { infos.add("efa.dir.user=" + Daten.efaBaseConfig.efaUserDirectory); } if (Daten.efaProgramDirectory != null) { infos.add("efa.dir.program=" + Daten.efaProgramDirectory); } if (Daten.efaPluginDirectory != null) { infos.add("efa.dir.plugin=" + Daten.efaPluginDirectory); } if (Daten.efaDocDirectory != null) { infos.add("efa.dir.doc=" + Daten.efaDocDirectory); } if (Daten.efaDataDirectory != null) { infos.add("efa.dir.data=" + Daten.efaDataDirectory); } if (Daten.efaCfgDirectory != null) { infos.add("efa.dir.cfg=" + Daten.efaCfgDirectory); } if (Daten.efaBakDirectory != null) { infos.add("efa.dir.bak=" + Daten.efaBakDirectory); } if (Daten.efaTmpDirectory != null) { infos.add("efa.dir.tmp=" + Daten.efaTmpDirectory); } } } // efa Plugin-Infos if (pluginInfos) { try { File dir = new File(Daten.efaPluginDirectory); if ((applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) && Logger.isDebugLogging()) { File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { infos.add("efa.plugin.file=" + file.getName() + ":" + file.length()); } } } Plugins plugins = Plugins.getPluginInfoFromLocalFile(); String[] names = plugins.getAllPluginNames(); for (String name : names) { infos.add("efa.plugin." + name + "=" + (Plugins.isPluginInstalled(name) ? "installed" : "not installed")); } } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, International.getString("Programminformationen konnten nicht ermittelt werden") + ": " + e.toString()); return null; } } // Java Infos if (javaInfos) { infos.add("java.version=" + System.getProperty("java.version")); infos.add("java.vendor=" + System.getProperty("java.vendor")); infos.add("java.home=" + System.getProperty("java.home")); infos.add("java.vm.version=" + System.getProperty("java.vm.version")); infos.add("java.vm.vendor=" + System.getProperty("java.vm.vendor")); infos.add("java.vm.name=" + System.getProperty("java.vm.name")); infos.add("os.name=" + System.getProperty("os.name")); infos.add("os.arch=" + System.getProperty("os.arch")); infos.add("os.version=" + System.getProperty("os.version")); if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { infos.add("user.home=" + System.getProperty("user.home")); infos.add("user.name=" + System.getProperty("user.name")); infos.add("user.dir=" + System.getProperty("user.dir")); infos.add("java.class.path=" + System.getProperty("java.class.path")); } } // Host Infos if (hostInfos) { if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { try { infos.add("host.name=" + InetAddress.getLocalHost().getCanonicalHostName()); infos.add("host.ip=" + InetAddress.getLocalHost().getHostAddress()); infos.add("host.interface=" + EfaUtil .getInterfaceInfo(NetworkInterface.getByInetAddress(InetAddress.getLocalHost()))); } catch (Exception eingore) { } } } // JAR methods if (jarInfos && Logger.isDebugLogging()) { try { String cp = System.getProperty("java.class.path"); while (cp != null && cp.length() > 0) { int pos = cp.indexOf(";"); if (pos < 0) { pos = cp.indexOf(":"); } String jarfile; if (pos >= 0) { jarfile = cp.substring(0, pos); cp = cp.substring(pos + 1); } else { jarfile = cp; cp = null; } if (jarfile != null && jarfile.length() > 0 && new File(jarfile).isFile()) { try { infos.add("java.jar.filename=" + jarfile); JarFile jar = new JarFile(jarfile); Enumeration _enum = jar.entries(); Object o; while (_enum.hasMoreElements() && (o = _enum.nextElement()) != null) { infos.add( "java.jar.content=" + o + ":" + (jar.getEntry(o.toString()) == null ? "null" : Long.toString(jar.getEntry(o.toString()).getSize()))); } jar.close(); } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, e.toString()); return null; } } } } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, International.getString("Programminformationen konnten nicht ermittelt werden") + ": " + e.toString()); return null; } } return infos; }
From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java
@Override public InternalPlugin parse(final File file) { JarFile jarFile = null; try {/*from w w w .j a v a2 s . c o m*/ LOG.info("Parsing descriptor for:" + file.getAbsolutePath()); boolean ignoreModules = true; jarFile = new JarFile(file); JarEntry descriptorEntry = findDescriptorEntry(jarFile.entries(), file.getAbsolutePath()); return parse(jarFile.getInputStream(descriptorEntry), ignoreModules, file.getName()); } catch (IOException e) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } catch (Exception e) { throw new PluginException(e.getMessage(), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { throw new PluginException( "Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } } } }
From source file:net.cliseau.composer.javatarget.PointcutParseException.java
/** * Update the manifest of a given JAR file to include CliSeAu's dependencies in the classpath list. * * This method modifies the "Class-Path" entry of the given JAR file's * manifest to include the paths of all runtime dependencies that are caused * by the instrumentation with the CliSeAu unit. * * @param targetJARFile The JAR file whose manifest to update. * @exception IOException Thrown when reading or writing the JAR file fails. * @todo Check whether this update is possible also with the JarFile API alone. *///from w w w .j av a 2 s.co m private void updateTargetManifest(final File targetJARFile) throws IOException, InvalidConfigurationException { // Step 1: Obtain the existing class path list from the target JAR file JarFile targetJAR = new JarFile(targetJARFile); Manifest targetManifest = targetJAR.getManifest(); LinkedList<String> classPathEntries; if (targetManifest != null) { String targetClassPath = targetManifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (targetClassPath == null) { targetClassPath = ""; } classPathEntries = new LinkedList<String>( Arrays.asList(targetClassPath.split(manifestClassPathSeparator))); } else { classPathEntries = new LinkedList<String>(); } // close the object again (this shall ensure that the command in // Step 4 can safely work on the file again) targetJAR.close(); // Step 2: Add all newly introduced runtime dependencies of CliSeAu classPathEntries.addAll(getInlinedDependencies()); // Step 3: Create a new manifest file with *only* the updated class path directive File manifestUpdate = File.createTempFile("MANIFEST", ".MF"); PrintWriter muWriter = new PrintWriter(manifestUpdate); muWriter.print("Class-path:"); muWriter.print(StringUtils.join(classPathEntries, manifestClassPathSeparator)); muWriter.println(); muWriter.close(); // Step 4: Run "jar" to update the JAR file with the new manifest; this // does not replace the JAR file's manifest with the new one, but // *update* *only* those entries in the JAR file's manifest which are // present in the new manifest. That is, only the class path settings are // updated and everything else remains intact. CommandRunner.exec(new String[] { aspectjConfig.getJarExecutable(), "umf", // update manifest manifestUpdate.getPath(), targetJARFile.getPath() }); // Step 5: cleanup manifestUpdate.delete(); }
From source file:org.jahia.utils.maven.plugin.DeployMojo.java
private boolean isJahiaModuleBundle(File file) { if (!file.exists()) { return false; }/*from w w w. j ava2 s . c om*/ // check the manifest JarFile jar = null; try { jar = new JarFile(file, false); return jar.getManifest().getMainAttributes().containsKey(new Attributes.Name("Jahia-Module-Type")); } catch (IOException e) { getLog().error(e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { getLog().warn(e); } } } return false; }
From source file:org.araqne.pkg.PackageManagerService.java
private Version getBundleVersion(File file) { JarFile jar = null; try {//w w w . j a v a2 s .co m jar = new JarFile(file); Attributes attrs = jar.getManifest().getMainAttributes(); return new Version(attrs.getValue("Bundle-Version")); } catch (IOException e) { logger.error("package manager: bundle version not found", e); return null; } finally { if (jar != null) try { jar.close(); } catch (IOException e) { } } }