List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) 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 w ww . ja v a 2s .c o 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:org.spoutcraft.launcher.launch.MinecraftClassLoader.java
private Class<?> findClassInjar(String name, File file) throws ClassNotFoundException { byte classByte[]; Class<?> result = null; JarFile jar = null; try {// w ww . j a v a2 s.c o m jar = new JarFile(file); JarEntry entry = jar.getJarEntry(name.replace(".", "/") + ".class"); if (entry != null) { InputStream is = jar.getInputStream(entry); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int next = is.read(); while (-1 != next) { byteStream.write(next); next = is.read(); } classByte = byteStream.toByteArray(); result = defineClass(name, classByte, 0, classByte.length, new CodeSource(file.toURI().toURL(), (CodeSigner[]) null)); loadedClasses.put(name, result); return result; } } catch (FileNotFoundException e) { // Assume temp file has been cleaned if the thread is interrupted if (!Thread.currentThread().isInterrupted()) { e.printStackTrace(); } } catch (ZipException zipEx) { System.out.println("Failed to open " + name + " from " + file.getPath()); zipEx.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { jar.close(); } catch (IOException ignore) { } } return null; }
From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java
private Properties getPluginProps(File file) throws IOException { Properties result = null;//w ww .j ava2 s . c o m JarFile jar = new JarFile(file); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().equals(PROPERTY_FILE_NAME)) { // That's it! Load props InputStream is = null; try { is = jar.getInputStream(entry); result = new Properties(); result.load(is); } finally { if (is != null) is.close(); } } } jar.close(); return result; }
From source file:es.jamisoft.comun.utils.compression.Jar.java
public void descomprimir(String lsDirDestino) { try {//from www . j a v a2 s . c om JarFile lzfFichero = new JarFile(isFicheroJar); Enumeration lenum = lzfFichero.entries(); JarArchiveEntry entrada = null; InputStream linput; for (; lenum.hasMoreElements(); linput.close()) { entrada = (JarArchiveEntry) lenum.nextElement(); linput = lzfFichero.getInputStream(entrada); byte labBytes[] = new byte[2048]; int liLeido = -1; String lsRutaDestino = lsDirDestino + File.separator + entrada.getName(); lsRutaDestino = lsRutaDestino.replace('\\', File.separatorChar); File lfRutaCompleta = new File(lsRutaDestino); String lsRuta = lfRutaCompleta.getAbsolutePath(); int liPosSeparator = lsRuta.lastIndexOf(File.separatorChar); lsRuta = lsRuta.substring(0, liPosSeparator); File ldDir = new File(lsRuta); boolean lbCreado = ldDir.mkdirs(); if (entrada.isDirectory()) { continue; } FileOutputStream loutput = new FileOutputStream(lfRutaCompleta); if (entrada.getSize() > 0L) { while ((liLeido = linput.read(labBytes, 0, 2048)) != -1) { loutput.write(labBytes, 0, liLeido); } } loutput.flush(); loutput.close(); } lzfFichero.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.jasper.compiler.JspUtil.java
public static InputStream getInputStream(String fname, JarFile jarFile, JspCompilationContext ctxt, ErrorDispatcher err) throws JasperException, IOException { InputStream in = null;//from w w w.j a v a2s . co m if (jarFile != null) { String jarEntryName = fname.substring(1, fname.length()); ZipEntry jarEntry = jarFile.getEntry(jarEntryName); if (jarEntry == null) { err.jspError("jsp.error.file.not.found", fname); } in = jarFile.getInputStream(jarEntry); } else { in = ctxt.getResourceAsStream(fname); } if (in == null) { err.jspError("jsp.error.file.not.found", fname); } return in; }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File jenkinsTemplateWar = new File(warTemplateFile); if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) { String message = "The given Jenkins template WAR [" + jenkinsTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);/* w w w . j av a 2s . c om*/ throw new IllegalStateException(message); } String pathProperty = perOrg ? configuration.getOrganizationIdentifier() : configuration.getProjectIdentifier(); String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL) + jenkinsPath + pathProperty + "/jenkins/"; deployedUrl.replace("//", "/"); URL deployedJenkinsUrl; try { deployedJenkinsUrl = new URL(deployedUrl); } catch (MalformedURLException e) { throw new RuntimeException(e); } String webappName = deployedJenkinsUrl.getPath(); if (webappName.startsWith("/")) { webappName = webappName.substring(1); } if (webappName.endsWith("/")) { webappName = webappName.substring(0, webappName.length() - 1); } webappName = webappName.replace("/", "#"); webappName = webappName + ".war"; // Calculate our final filename. String deployLocation = targetWebappsDir + webappName; File jenkinsDeployFile = new File(deployLocation); if (jenkinsDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct JENKINS_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar), jenkinsTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into its deployment location so that it can be picked up and deployed by the app server. FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:org.datavyu.util.NativeLoader.java
/** * Unpacks a native application to a temporary location so that it can be * utilized from within java code./*from www . j a v a 2s. co m*/ * * @param appJar The jar containing the native app that you want to unpack. * @return The path of the native app as unpacked to a temporary location. * * @throws Exception If unable to unpack the native app to a temporary * location. */ public static String unpackNativeApp(final String appJar) throws Exception { final String nativeLibraryPath; if (nativeLibFolder == null) { nativeLibraryPath = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "nativelibs"; nativeLibFolder = new File(nativeLibraryPath); if (!nativeLibFolder.exists()) { nativeLibFolder.mkdir(); } } // Search the class path for the application jar. JarFile jar = null; // BugID: 26178921 -- We need to inspect the surefire test class path as // well as the regular class path property so that we can scan dependencies // during tests. String searchPath = System.getProperty("surefire.test.class.path") + File.pathSeparator + System.getProperty("java.class.path"); for (String s : searchPath.split(File.pathSeparator)) { // Success! We found a matching jar. if (s.endsWith(appJar + ".jar") || s.endsWith(appJar)) { jar = new JarFile(s); } } // If we found a jar - it should contain the desired application. // decompress as needed. if (jar != null) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry inFile = entries.nextElement(); File outFile = new File(nativeLibFolder, inFile.getName()); // If the file from the jar is a directory, create it. if (inFile.isDirectory()) { outFile.mkdir(); // The file from the jar is regular - decompress it. } else { InputStream in = jar.getInputStream(inFile); // Create a temporary output location for the library. FileOutputStream out = new FileOutputStream(outFile); BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER); int count; byte[] data = new byte[BUFFER]; while ((count = in.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); out.close(); in.close(); } loadedLibs.add(outFile); } // Unable to find jar file - abort decompression. } else { System.err.println("Unable to find jar file for unpacking: " + appJar + ". Java classpath is:"); for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) { System.err.println(" " + s); } throw new Exception("Unable to find '" + appJar + "' for unpacking."); } return nativeLibFolder.getAbsolutePath(); }
From source file:javadepchecker.Main.java
public void processJar(JarFile jar) throws IOException { for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); String name = entry.getName(); if (!entry.isDirectory() && name.endsWith(".class")) { this.current.add(name); InputStream stream = jar.getInputStream(entry); new ClassReader(stream).accept(this, 0); }//from ww w . j a v a 2 s . c o m } }
From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorBuilder.java
public GoPluginDescriptor build(File pluginJarFile, boolean isBundledPlugin) { if (!pluginJarFile.exists()) { throw new RuntimeException( String.format("Plugin jar does not exist: %s", pluginJarFile.getAbsoluteFile())); }/*from www.j a v a 2 s . com*/ InputStream pluginXMLStream = null; JarFile jarFile = null; try { jarFile = new JarFile(pluginJarFile); ZipEntry entry = jarFile.getEntry(PLUGIN_XML); if (entry == null) { return GoPluginDescriptor.usingId(pluginJarFile.getName(), pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin); } pluginXMLStream = jarFile.getInputStream(entry); return GoPluginDescriptorParser.parseXML(pluginXMLStream, pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin); } catch (Exception e) { LOGGER.warn("Could not load plugin with jar filename:" + pluginJarFile.getName(), e); String cause = e.getCause() != null ? String.format("%s. Cause: %s", e.getMessage(), e.getCause().getMessage()) : e.getMessage(); return GoPluginDescriptor .usingId(pluginJarFile.getName(), pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin) .markAsInvalid(Arrays.asList( String.format("Plugin with ID (%s) is not valid: %s", pluginJarFile.getName(), cause)), e); } finally { IOUtils.closeQuietly(pluginXMLStream); closeQuietly(jarFile); } }
From source file:org.apache.hyracks.maven.license.GenerateFileMojo.java
private void resolveContent(Project project, JarFile jarFile, JarEntry entry, UnaryOperator<String> transformer, BiConsumer<Project, String> contentConsumer, final String name) throws IOException { String text = IOUtils.toString(jarFile.getInputStream(entry), StandardCharsets.UTF_8); text = transformer.apply(text);//w w w.j a va2 s . c om text = LicenseUtil.trim(text); if (text.length() == 0) { getLog().warn("Ignoring empty " + name + " file ( " + entry + ") for " + project.gav()); } else { contentConsumer.accept(project, text); getLog().debug("Resolved " + name + " text for " + project.gav() + ": \n" + text); } }