List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:com.eviware.soapui.plugins.JarClassLoader.java
private void addScriptsIn(JarFile jarFile) throws IOException { boolean hasScripts = false; if (containsScripts(jarFile)) { File scriptsDirectory = Tools.createTemporaryDirectory(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (isScript(jarEntry)) { String pathToScript = jarEntry.getName(); File outputFile = null; int lastSlashIndex = pathToScript.lastIndexOf('/'); if (lastSlashIndex >= 0) { File packageDirectory = new File(scriptsDirectory, pathToScript.substring(0, lastSlashIndex)); if (!packageDirectory.exists() || !packageDirectory.isDirectory()) { if (!packageDirectory.mkdirs()) { log.error("Failed to create directory for [" + pathToScript + "]"); packageDirectory = null; }/* w w w. j ava 2 s .c o m*/ } if (packageDirectory != null) { outputFile = new File(packageDirectory, pathToScript.substring(lastSlashIndex + 1)); } } if (outputFile != null) { FileUtils.copyInputStreamToFile(jarFile.getInputStream(jarEntry), outputFile); hasScripts = true; } } } /* if (hasScripts) { URL scriptsUrl = scriptsDirectory.toURI().toURL(); SoapUIPro.getSoapUIGroovyClassLoader().addURL(scriptsUrl); scriptClassLoader = new GroovyClassLoader(SoapUIPro.getSoapUIGroovyClassLoader()); scriptClassLoader.addURL(scriptsUrl); } */ } }
From source file:org.openmrs.module.ModuleUtil.java
/** * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory * * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null, * then only that path/file is expanded. * * @param fileToExpand file pointing at a .jar * @param tmpModuleDir directory in which to place the files * @param name filename inside of the jar to look for and expand * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir * relating to <code>name</code>. if false will start directory structure at * <code>name</code> *///from www.ja v a 2 s .c o m public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath) throws IOException { JarFile jarFile = null; InputStream input = null; String docBase = tmpModuleDir.getAbsolutePath(); try { jarFile = new JarFile(fileToExpand); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundName = (name == null); // loop over all of the elements looking for the match to 'name' while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (name == null || jarEntry.getName().startsWith(name)) { String entryName = jarEntry.getName(); // trim out the name path from the name of the new file if (!keepFullPath && name != null) { entryName = entryName.replaceFirst(name, ""); } // if it has a slash, it's in a directory int last = entryName.lastIndexOf('/'); if (last >= 0) { File parent = new File(docBase, entryName.substring(0, last)); parent.mkdirs(); log.debug("Creating parent dirs: " + parent.getAbsolutePath()); } // we don't want to "expand" directories or empty names if (entryName.endsWith("/") || "".equals(entryName)) { continue; } input = jarFile.getInputStream(jarEntry); expand(input, docBase, entryName); input.close(); input = null; foundName = true; } } if (!foundName) { log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath()); } } catch (IOException e) { log.warn("Unable to delete tmpModuleFile on error", e); throw e; } finally { try { input.close(); } catch (Exception e) { /* pass */} try { jarFile.close(); } catch (Exception e) { /* pass */} } }
From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java
private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException { JarFile jarFile = null; try {// w w w. ja v a 2 s . c o m jarFile = new JarFile(jar); JarEntry entry = jarFile.getJarEntry(subPath); if (entry == null) { response.sendError(404); return; } // fallback for requesting a directory without a trailing / // this leads to a jarentry which is not null, and not a directory and of size 0 // this shouldn't be if (!entry.isDirectory() && entry.getSize() == 0) { if (!subPath.endsWith("/")) { JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/"); if (entryWithSlash != null && entryWithSlash.isDirectory()) { entry = entryWithSlash; } } } if (entry.isDirectory()) { for (String indexFile : DEFAULT_INDEX_FILES) { entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile); if (entry != null) { break; } } } if (entry == null) { response.sendError(404); return; } response.setContentLength((int) entry.getSize()); String mimetype = getMimeType(entry.getName()); response.setContentType(mimetype); InputStream input = jarFile.getInputStream(entry); try { ByteStreams.copy(input, response.getOutputStream()); } finally { input.close(); } } finally { if (jarFile != null) { jarFile.close(); } } }
From source file:UnpackedJarFile.java
public static void copyToPackedJar(JarFile inputJar, File outputFile) throws IOException { if (inputJar.getClass() == JarFile.class) { // this is a plain old jar... nothign special copyFile(new File(inputJar.getName()), outputFile); } else if (inputJar instanceof NestedJarFile && ((NestedJarFile) inputJar).isPacked()) { NestedJarFile nestedJarFile = (NestedJarFile) inputJar; JarFile baseJar = nestedJarFile.getBaseJar(); String basePath = nestedJarFile.getBasePath(); if (baseJar instanceof UnpackedJarFile) { // our target jar is just a file in upacked jar (a plain old directory)... now // we just need to find where it is and copy it to the outptu copyFile(((UnpackedJarFile) baseJar).getFile(basePath), outputFile); } else {//from ww w .ja v a2s. c o m // out target is just a plain old jar file directly accessabel from the file system copyFile(new File(baseJar.getName()), outputFile); } } else { // copy out the module contents to a standalone jar file (entry by entry) JarOutputStream out = null; try { out = new JarOutputStream(new FileOutputStream(outputFile)); byte[] buffer = new byte[4096]; Enumeration entries = inputJar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); InputStream in = inputJar.getInputStream(entry); try { out.putNextEntry(new ZipEntry(entry.getName())); try { int count; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } } finally { out.closeEntry(); } } finally { close(in); } } } finally { close(out); } } }
From source file:org.openmrs.module.ModuleFileParser.java
/** * Get the module// w ww . ja va2 s . c om * * @return new module object */ public Module parse() throws ModuleException { Module module = null; JarFile jarfile = null; InputStream configStream = null; try { try { jarfile = new JarFile(moduleFile); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"), moduleFile.getName(), e); } // look for config.xml in the root of the module ZipEntry config = jarfile.getEntry("config.xml"); if (config == null) { throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"), moduleFile.getName()); } // get a config file stream try { configStream = jarfile.getInputStream(config); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"), moduleFile.getName(), e); } // turn the config file into an xml document Document configDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a // DTD) we return an InputSource // with no data at the end, causing the parser to ignore // the DTD. return new InputSource(new StringReader("")); } }); configDoc = db.parse(configStream); } catch (Exception e) { log.error("Error parsing config.xml: " + configStream.toString(), e); OutputStream out = null; String output = ""; try { out = new ByteArrayOutputStream(); // Now copy bytes from the URL to the output stream byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = configStream.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } output = out.toString(); } catch (Exception e2) { log.warn("Another error parsing config.xml", e2); } finally { try { out.close(); } catch (Exception e3) { } } log.error("config.xml content: " + output); throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"), moduleFile.getName(), e); } Element rootNode = configDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion").trim(); if (!validConfigVersions.contains(configVersion)) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion", new Object[] { configVersion }, Context.getLocale()), moduleFile.getName()); } String name = getElement(rootNode, configVersion, "name").trim(); String moduleId = getElement(rootNode, configVersion, "id").trim(); String packageName = getElement(rootNode, configVersion, "package").trim(); String author = getElement(rootNode, configVersion, "author").trim(); String desc = getElement(rootNode, configVersion, "description").trim(); String version = getElement(rootNode, configVersion, "version").trim(); // do some validation if (name == null || name.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"), moduleFile.getName()); } if (moduleId == null || moduleId.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name); } if (packageName == null || packageName.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name); } // create the module object module = new Module(name, moduleId, packageName, author, desc, version); // find and load the activator class module.setActivatorName(getElement(rootNode, configVersion, "activator").trim()); module.setRequireDatabaseVersion( getElement(rootNode, configVersion, "require_database_version").trim()); module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim()); module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim()); module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion)); module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion)); module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion)); module.setAdvicePoints(getAdvice(rootNode, configVersion, module)); module.setExtensionNames(getExtensions(rootNode, configVersion)); module.setPrivileges(getPrivileges(rootNode, configVersion)); module.setGlobalProperties(getGlobalProperties(rootNode, configVersion)); module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version)); module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile)); module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion)); module.setConfig(configDoc); module.setMandatory(getMandatory(rootNode, configVersion, jarfile)); module.setFile(moduleFile); module.setConditionalResources(getConditionalResources(rootNode)); } finally { try { jarfile.close(); } catch (Exception e) { log.warn("Unable to close jarfile: " + jarfile, e); } if (configStream != null) { try { configStream.close(); } catch (Exception io) { log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io); } } } return module; }
From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java
private void extractHtmlReportSummary() throws IOException, URISyntaxException { final String path = "html-summary-report"; final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); forceMkdir(reportsDirectory);// w w w. j a v a 2 s. c o m if (jarFile.isFile()) { // Run with JAR file JarFile jar = new JarFile(jarFile); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.startsWith(path)) { //filter according to the path File file = getFile(reportsDirectory, substringAfter(name, path)); if (jarEntry.isDirectory()) { forceMkdir(file); } else { forceMkdir(file.getParentFile()); if (!file.exists()) { copyInputStreamToFile(jar.getInputStream(jarEntry), file); } } } } jar.close(); } else { // Run with IDE URL url = getClass().getResource("/" + path); if (url != null) { File apps = FileUtils.toFile(url); if (apps.isDirectory()) { copyDirectory(apps, reportsDirectory); } else { throw new IllegalStateException( format("Internal resource '%s' should be a directory.", apps.getAbsolutePath())); } } else { throw new IllegalStateException(format("Internal resource '/%s' should be here.", path)); } } }
From source file:org.openmrs.util.OpenmrsUtil.java
/** * Opens input stream for given resource. This method behaves differently for different URL * types://from ww w . ja v a 2 s . com * <ul> * <li>for <b>local files</b> it returns buffered file input stream;</li> * <li>for <b>local JAR files</b> it reads resource content into memory buffer and returns byte * array input stream that wraps those buffer (this prevents locking JAR file);</li> * <li>for <b>common URL's</b> this method simply opens stream to that URL using standard URL * API.</li> * </ul> * It is not recommended to use this method for big resources within JAR files. * * @param url resource URL * @return input stream for given resource * @throws IOException if any I/O error has occurred */ public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { // JAR URL points to a root entry throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) {// non-local JAR file URL return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyFile(in, out); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } }
From source file:net.rim.ejde.internal.packaging.PackagingManager.java
/** * Checks if a jar file is a MidletJar created by rapc. * * @param f// w ww . j a v a 2 s . co m * @return */ static public int getJarFileType(File f) { int type = 0x0; if (!f.exists()) { return type; } java.util.jar.JarFile jar = null; try { jar = new java.util.jar.JarFile(f, false); java.util.jar.Manifest manifest = jar.getManifest(); if (manifest != null) { java.util.jar.Attributes attributes = manifest.getMainAttributes(); String profile = attributes.getValue("MicroEdition-Profile"); if (profile != null) { if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) { type = type | MIDLET_JAR; } } } Enumeration<JarEntry> entries = jar.entries(); JarEntry entry; String entryName; InputStream is = null; IClassFileReader classFileReader = null; // check the attribute of the class files in the jar file for (; entries.hasMoreElements();) { entry = entries.nextElement(); entryName = entry.getName(); if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) { is = jar.getInputStream(entry); classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL); if (isEvisceratedClass(classFileReader)) { type = type | EVISCERATED_JAR; break; } } } } catch (IOException e) { _log.error(e.getMessage()); } finally { try { if (jar != null) { jar.close(); } } catch (IOException e) { _log.error(e.getMessage()); } } return type; }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
private String read(JarFile car, ZipEntry entry) throws IOException { try (InputStream is = car.getInputStream(entry); Reader r = new InputStreamReader(is); BufferedReader br = new BufferedReader(r)) { StringBuilder sb = new StringBuilder(); String line;/* www.ja v a2 s .c o m*/ while ((line = br.readLine()) != null) sb.append(line).append("\n"); return sb.toString(); } }
From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java
private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs) throws IOException { Attributes attrs;// w w w . j av a 2 s. c om if (jar.getManifest() == null) return null; JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME); if (manifest_entry == null) manifest_entry = jar.stream() .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst() .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check. attrs = jar.getManifest().getMainAttributes(); String modSide = attrs.getValue(LibraryManager.MODSIDE); if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide)) return null; if (attrs.containsKey(MODCONTAINSDEPS)) { for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) { if (!dep.endsWith(".jar")) { FMLLog.log.error("Contained Dep is not a jar file: {}", dep); throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep); } if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null) dep = "META-INF/libraries/" + dep; JarEntry depEntry = jar.getJarEntry(dep); if (depEntry == null) { FMLLog.log.error("Contained Dep is not in the jar: {}", dep); throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep); } String depEndName = new File(dep).getName(); // extract last part of name if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) { FMLLog.log.error("Skipping dep at request: {}", dep); continue; } Attributes meta = null; byte[] data = null; byte[] manifest_data = null; JarEntry metaEntry = jar.getJarEntry(dep + ".meta"); if (metaEntry != null) { manifest_data = readAll(jar.getInputStream(metaEntry)); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); } else { data = readAll(jar.getInputStream(depEntry)); try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar... { ZipEntry ze = null; while ((ze = zi.getNextEntry()) != null) { if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) { manifest_data = readAll(zi); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); break; } } } } if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13? { boolean found = false; for (File dir : modDirs) { File target = new File(dir, depEndName); if (target.exists()) { FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath()); found = true; } } if (!found) { File target = new File(modDirs[0], depEndName); FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); try { Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); extractPacked(target, modlist, modDirs); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } else { try { Artifact artifact = readArtifact(modlist.getRepository(), meta); File target = artifact.getFile(); if (target.exists()) { FMLLog.log.debug( "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName()); if (!ENABLE_AUTO_MOD_MOVEMENT) { Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down. if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } else { FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); if (artifact.isSnapshot()) { SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta()); json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5))); json.write(artifact.getSnapshotMeta()); } if (!DISABLE_EXTERNAL_MANIFEST) { File meta_target = new File(target.getAbsolutePath() + ".meta"); Files.write(manifest_data, meta_target); } Pair<?, ?> child = extractPacked(target, modlist, modDirs); if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } catch (NumberFormatException nfe) { FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage( "An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } } if (attrs.containsKey(MAVEN_ARTIFACT)) { Artifact artifact = readArtifact(modlist.getRepository(), attrs); modlist.add(artifact); return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry))); } return null; }