List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:net.minecraftforge.fml.common.discovery.JarDiscoverer.java
@Override public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table) { List<ModContainer> foundMods = Lists.newArrayList(); FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName()); JarFile jar = null; try {/*from ww w . j av a2s . co m*/ jar = new JarFile(candidate.getModContainer()); ZipEntry modInfo = jar.getEntry("mcmod.info"); MetadataCollection mc = null; if (modInfo != null) { FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName()); InputStream inputStream = jar.getInputStream(modInfo); try { mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName()); } finally { IOUtils.closeQuietly(inputStream); } } else { FMLLog.fine("The mod container %s appears to be missing an mcmod.info file", candidate.getModContainer().getName()); mc = MetadataCollection.from(null, ""); } for (ZipEntry ze : Collections.list(jar.entries())) { if (ze.getName() != null && ze.getName().startsWith("__MACOSX")) { continue; } Matcher match = classFile.matcher(ze.getName()); if (match.matches()) { ASMModParser modParser; try { InputStream inputStream = jar.getInputStream(ze); try { modParser = new ASMModParser(inputStream); } finally { IOUtils.closeQuietly(inputStream); } candidate.addClassEntry(ze.getName()); } catch (LoaderException e) { FMLLog.log(Level.ERROR, e, "There was a problem reading the entry %s in the jar %s - probably a corrupt zip", ze.getName(), candidate.getModContainer().getPath()); jar.close(); throw e; } modParser.validate(); modParser.sendToTable(table, candidate); ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate); if (container != null) { table.addContainer(container); foundMods.add(container); container.bindMetadata(mc); container.setClassVersion(modParser.getClassVersion()); } } } } catch (Exception e) { FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored", candidate.getModContainer().getName()); } finally { Java6Utils.closeZipQuietly(jar); } return foundMods; }
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 ww w.j a v a 2 s. c o m 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.databasepreservation.visualization.utils.SolrUtils.java
public static void setupSolrCloudConfigsets(String zkHost) { // before anything else, try to get a zookeeper client CloudSolrClient zkClient = new CloudSolrClient(zkHost); // get resources and copy them to a temporary directory Path databaseDir = null;//from ww w . j ava 2s . co m Path tableDir = null; Path savedSearchesDir = null; try { final File jarFile = new File( SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI()); // if it is a directory the application in being run from an IDE // in that case do not setup (assuming setup is done) if (!jarFile.isDirectory()) { databaseDir = Files.createTempDirectory("dbv_db_"); tableDir = Files.createTempDirectory("dbv_tab_"); savedSearchesDir = Files.createTempDirectory("dbv_tab_"); final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); String nameWithoutOriginPart = null; Path destination = null; if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1); destination = databaseDir; } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1); destination = tableDir; } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) { nameWithoutOriginPart = name .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1); destination = savedSearchesDir; } else { continue; } Path output = destination.resolve(nameWithoutOriginPart); if (name.endsWith("/")) { Files.createDirectories(output); } else { InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name); output = Files.createFile(output); OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE, StandardOpenOption.WRITE); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } } jar.close(); } } catch (IOException | URISyntaxException e) { LOGGER.error("Could not extract Solr configset", e); if (databaseDir != null) { try { FileUtils.deleteDirectoryRecursive(databaseDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1); } } if (tableDir != null) { try { FileUtils.deleteDirectoryRecursive(tableDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1); } } databaseDir = null; tableDir = null; } // copy configurations to solr if (databaseDir != null && tableDir != null) { try { zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE); } catch (IOException e) { LOGGER.debug("IO error uploading database config to solr cloud", e); } try { zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE); } catch (IOException e) { LOGGER.debug("IO error uploading table config to solr cloud", e); } try { zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES); } catch (IOException e) { LOGGER.debug("IO error uploading saved searches config to solr cloud", e); } try { FileUtils.deleteDirectoryRecursive(databaseDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1); } try { FileUtils.deleteDirectoryRecursive(tableDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1); } try { FileUtils.deleteDirectoryRecursive(savedSearchesDir); } catch (IOException e1) { LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1); } } try { zkClient.close(); } catch (IOException e) { LOGGER.debug("IO error closing connection to solr cloud", e); } }
From source file:org.interreg.docexplore.GeneralConfigPanel.java
String browseClasses(File file) { try {//from w w w. j a va2s .c o m List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>(); List<Class<?>> analysisPlugins = new LinkedList<Class<?>>(); List<Class<?>> clientPlugins = new LinkedList<Class<?>>(); List<Class<?>> serverPlugins = new LinkedList<Class<?>>(); List<Class<?>> inputPlugins = new LinkedList<Class<?>>(); List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4), file.getName()); urls.add(file.toURI().toURL()); URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}), this.getClass().getClassLoader()); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0) continue; String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.'); Class<?> clazz = null; try { clazz = loader.loadClass(className); System.out.println("Reading " + className); } catch (NoClassDefFoundError e) { System.out.println("Couldn't read " + className); } if (clazz == null) continue; if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue; if (MetaDataPlugin.class.isAssignableFrom(clazz)) metaDataPlugins.add(clazz); if (AnalysisPlugin.class.isAssignableFrom(clazz)) analysisPlugins.add(clazz); if (ClientPlugin.class.isAssignableFrom(clazz)) clientPlugins.add(clazz); if (ServerPlugin.class.isAssignableFrom(clazz)) serverPlugins.add(clazz); if (InputPlugin.class.isAssignableFrom(clazz)) inputPlugins.add(clazz); } jarFile.close(); @SuppressWarnings("unchecked") Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size() + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()]; if (classes.length == 0) throw new Exception("Invalid plugin (no entry points were found)."); int cnt = 0; for (Class<?> clazz : metaDataPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : analysisPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : clientPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : serverPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : inputPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") { public String toString() { return first + " (" + second + ")"; } }; @SuppressWarnings("unchecked") Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this, "Please select an entry point for the plugin:", "Plugin entry point", JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]); if (res != null) return res.first; } catch (Throwable e) { ErrorHandler.defaultHandler.submit(e); } return null; }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlModuleFromCompiledModule() throws IOException { compile("modules/single/module.ceylon"); File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6"); assertTrue(carFile.exists());//w ww. j av a 2 s.c om JarFile car = new JarFile(carFile); // just to be sure ZipEntry bogusEntry = car.getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/BOGUS"); assertNull(bogusEntry); ZipEntry moduleClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class"); assertNotNull(moduleClass); car.close(); compile("modules/single/subpackage/Subpackage.ceylon"); // MUST reopen it car = new JarFile(carFile); ZipEntry subpackageClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/Subpackage.class"); assertNotNull(subpackageClass); car.close(); }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlNoPomManifest() throws IOException { ErrorCollector c = new ErrorCollector(); assertCompilesOk(c, getCompilerTask(Arrays.asList("-nopom", "-out", destDir), c, "modules/pom/a/module.ceylon", "modules/pom/b/module.ceylon").call2()); final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.pom.b"; final String moduleVersion = "1"; File carFile = getModuleArchive(moduleName, moduleVersion); assertTrue(carFile.exists());/*from w ww . ja v a 2 s. c om*/ JarFile car = new JarFile(carFile); ZipEntry pomFile = car .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.xml"); assertNull(pomFile); ZipEntry propertiesFile = car .getEntry("META-INF/maven/com.redhat.ceylon.compiler.java.test.cmr.modules.pom/b/pom.properties"); assertNull(propertiesFile); car.close(); }
From source file:org.apache.struts2.jasper.compiler.TldLocationsCache.java
/** * Scans the given JarURLConnection for TLD files located in META-INF * (or a subdirectory of it), adding an implicit map entry to the taglib * map for any TLD that has a <uri> element. * * @param conn The JarURLConnection to the JAR file to scan * @param ignore true if any exceptions raised when processing the given * JAR should be ignored, false otherwise *///w w w .jav a2 s . c o m private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException { JarFile jarFile = null; String resourcePath = conn.getJarFileURL().toString(); try { if (redeployMode) { conn.setUseCaches(false); } jarFile = conn.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (!name.startsWith("META-INF/")) continue; if (!name.endsWith(".tld")) continue; InputStream stream = jarFile.getInputStream(entry); try { String uri = getUriFromTld(resourcePath, stream); // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { mappings.put(uri, new String[] { resourcePath, name }); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { // do nothing } } } } } catch (Exception ex) { if (!redeployMode) { // if not in redeploy mode, close the jar in case of an error if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } if (!ignore) { throw new JasperException(ex); } } finally { if (redeployMode) { // if in redeploy mode, always close the jar if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } } }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Cycles through an enumeration of JarEntries, contained within the * dependency, and returns a list of the class names. This does not include * core Java package names (i.e. java.* or javax.*). * * @param dependency the dependency being analyzed * @return an list of fully qualified class names *///ww w . j ava 2 s . c om private List<ClassNameInformation> collectClassNames(Dependency dependency) { final List<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>(); JarFile jar = null; try { jar = new JarFile(dependency.getActualFilePath()); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String name = entry.getName().toLowerCase(); //no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs. if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) { final ClassNameInformation className = new ClassNameInformation( name.substring(0, name.length() - 6)); classNames.add(className); } } } catch (IOException ex) { LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName()); LOGGER.debug("", ex); } finally { if (jar != null) { try { jar.close(); } catch (IOException ex) { LOGGER.trace("", ex); } } } return classNames; }
From source file:net.fabricmc.installer.installer.ClientInstaller.java
public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar) throws IOException { progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0); JarFile jarFile = new JarFile(fabricJar); Attributes attributes = jarFile.getManifest().getMainAttributes(); String id = "fabric-" + attributes.getValue("FabricVersion"); System.out.println(Translator.getString("gui.installing") + " " + id); File versionsFolder = new File(mcDir, "versions"); File fabricVersionFolder = new File(versionsFolder, id); File mcVersionFolder = new File(versionsFolder, version); File fabricJsonFile = new File(fabricVersionFolder, id + ".json"); File tempWorkDir = new File(fabricVersionFolder, "temp"); ZipUtil.unpack(fabricJar, tempWorkDir, name -> { if (name.startsWith(Reference.INSTALLER_METADATA_FILENAME)) { return name; } else {/* w w w .j a v a 2s. co m*/ return null; } }); InstallerMetadata metadata = new InstallerMetadata(tempWorkDir); File mcJarFile = new File(mcVersionFolder, version + ".jar"); if (fabricVersionFolder.exists()) { progress.updateProgress(Translator.getString("install.client.removeOld"), 10); FileUtils.deleteDirectory(fabricVersionFolder); } fabricVersionFolder.mkdirs(); progress.updateProgress(Translator.getString("install.client.createJson"), 20); String mcJson = FileUtils.readFileToString(mcJarFile, Charset.defaultCharset()); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonObject versionJson = new JsonObject(); versionJson.addProperty("id", id); versionJson.addProperty("type", "release"); versionJson.addProperty("time", Utils.ISO_8601.format(fabricJar.lastModified())); versionJson.addProperty("releaseTime", Utils.ISO_8601.format(fabricJar.lastModified())); versionJson.addProperty("mainClass", metadata.getMainClass()); versionJson.addProperty("inheritsFrom", version); JsonArray gameArgs = new JsonArray(); JsonObject arguments = new JsonObject(); List<String> metadataTweakers = metadata.getTweakers("client", "common"); if (metadataTweakers.size() > 1) { throw new RuntimeException("Not supporting > 1 tweaker yet!"); } metadata.getArguments("client", "common").forEach(gameArgs::add); gameArgs.add("--tweakClass"); gameArgs.add(metadataTweakers.get(0)); arguments.add("game", gameArgs); versionJson.add("arguments", arguments); JsonArray libraries = new JsonArray(); addDep(Reference.PACKAGE_FABRIC + ":" + Reference.NAME_FABRIC_LOADER + ":" + attributes.getValue("FabricVersion"), "http://maven.modmuss50.me/", libraries); for (InstallerMetadata.LibraryEntry entry : metadata.getLibraries("client", "common")) { libraries.add(entry.toVanillaEntry()); } versionJson.add("libraries", libraries); FileUtils.write(fabricJsonFile, gson.toJson(versionJson), "UTF-8"); jarFile.close(); progress.updateProgress(Translator.getString("install.client.cleanDir"), 90); FileUtils.deleteDirectory(tempWorkDir); progress.updateProgress(Translator.getString("install.success"), 100); }
From source file:org.wso2.carbon.integration.common.utils.FileManager.java
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory) throws URISyntaxException, IOException { File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI()); File destinationFileDirectory = new File(destinationDirectory); JarOutputStream jarOutputStream = null; InputStream inputStream = null; try {/* www.java 2 s .c om*/ JarFile jarFile = new JarFile(sourceFile); String fileName = jarFile.getName(); String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); File destinationFile = new File(destinationFileDirectory, fileNameLastPart); jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { try { JarEntry jarEntry = entries.nextElement(); inputStream = jarFile.getInputStream(jarEntry); //jarOutputStream.putNextEntry(jarEntry); //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName())); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { jarOutputStream.write(buffer, 0, bytesRead); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (jarOutputStream != null) { try { jarOutputStream.flush(); jarOutputStream.closeEntry(); } catch (IOException e) { log.warn("Error while closing jar out stream"); } } if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { log.warn("Error while closing jar file"); } } } } } finally { if (jarOutputStream != null) { try { jarOutputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Error while closing input stream"); } } } }