List of usage examples for java.util.jar JarFile getJarEntry
public JarEntry getJarEntry(String name)
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;/*from w w w . ja v a 2 s .c o m*/ 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; }
From source file:cc.pp.analyzer.paoding.knife.PaodingMaker.java
@SuppressWarnings("resource") private static long getFileLastModified(File file) throws IOException { String path = file.getPath(); int jarIndex = path.indexOf(".jar!"); if (jarIndex == -1) { return file.lastModified(); } else {/*from w ww .j ava2 s .com*/ path = path.replaceAll("%20", " ").replaceAll("\\\\", "/"); jarIndex = path.indexOf(".jar!"); int protocalIndex = path.indexOf(":"); String jarPath = path.substring(protocalIndex + ":".length(), jarIndex + ".jar".length()); File jarPathFile = new File(jarPath); JarFile jarFile; try { jarFile = new JarFile(jarPathFile); String entryPath = path.substring(jarIndex + ".jar!/".length()); JarEntry entry = jarFile.getJarEntry(entryPath); return entry.getTime(); } catch (IOException e) { System.err.println("error in handler path=" + path); System.err.println("error in handler jarPath=" + jarPath); throw e; } } }
From source file:net.paoding.analysis.knife.PaodingMaker.java
private static long getFileLastModified(File file) throws IOException { String path = file.getPath(); int jarIndex = path.indexOf(".jar!"); if (jarIndex == -1) { return file.lastModified(); } else {//from ww w.j a v a2 s . c o m path = path.replaceAll("%20", " ").replaceAll("\\\\", "/"); jarIndex = path.indexOf(".jar!"); int protocalIndex = path.indexOf(":"); String jarPath = path.substring(protocalIndex + ":".length(), jarIndex + ".jar".length()); File jarPathFile = new File(jarPath); JarFile jarFile; try { jarFile = new JarFile(jarPathFile); String entryPath = path.substring(jarIndex + ".jar!/".length()); JarEntry entry = jarFile.getJarEntry(entryPath); return entry.getTime(); } catch (IOException e) { System.err.println("error in handler path=" + path); System.err.println("error in handler jarPath=" + jarPath); throw e; } } }
From source file:com.bbxiaoqu.api.util.Utils.java
/** * ???MD5/*from w ww. ja v a2 s . co m*/ */ public static String getFileSignatureMd5(String targetFile) { try { JarFile jarFile = new JarFile(targetFile); // ?RSA JarEntry jarEntry = jarFile.getJarEntry("AndroidManifest.xml"); if (jarEntry != null) { InputStream is = jarFile.getInputStream(jarEntry); byte[] buffer = new byte[8192]; while (is.read(buffer) > 0) { // do nothing } is.close(); Certificate[] certs = jarEntry == null ? null : jarEntry.getCertificates(); if (certs != null && certs.length > 0) { String rsaPublicKey = String.valueOf(certs[0].getPublicKey()); return getMD5(rsaPublicKey); } } } catch (IOException e) { W("occur IOException when get file signature", e); } return ""; }
From source file:com.liferay.ide.project.core.util.ProjectImportUtil.java
/** * This method is used to validate whether the given plugin binary is a valid Liferay Plugin Archieve * * @param binaryFile//from w ww . j a v a2 s .co m * - the binary file to be validated * @return */ public static boolean isValidLiferayPlugin(File binaryFile) { boolean isValid = false; JarFile pluginBinary = null; try { pluginBinary = new JarFile(binaryFile); BinaryProjectRecord tempRecord = new BinaryProjectRecord(binaryFile); // Check for liferay-plugin-package.properties or liferay-plugin-package.xml JarEntry lfrPluginPkgPropsEntry = pluginBinary .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_FILE)); JarEntry lfrPluginPkgXmlEntry = pluginBinary.getJarEntry( getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_XML_FILE)); if (lfrPluginPkgPropsEntry != null || lfrPluginPkgXmlEntry != null) { isValid = true; } if (tempRecord.isHook()) { isValid = (isValid && pluginBinary .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_HOOK_XML_FILE)) != null); } else if (tempRecord.isLayoutTpl()) { isValid = (isValid || pluginBinary .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_LAYOUTTPL_XML_FILE)) != null); } else if (tempRecord.isPortlet()) { isValid = (isValid && pluginBinary .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PORTLET_XML_FILE)) != null); } else if (tempRecord.isTheme()) { isValid = (isValid || pluginBinary.getJarEntry( getConfigFileLocation(ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE)) != null); } if (!isValid) { return isValid; } else { // check if its a valid web Archieve isValid = isValid || pluginBinary.getJarEntry(getConfigFileLocation(ILiferayConstants.WEB_XML_FILE)) != null; } } catch (IOException e) { isValid = false; } finally { if (pluginBinary != null) { try { pluginBinary.close(); } catch (IOException e) { } } } return isValid; }
From source file:com.jrummyapps.busybox.signing.ZipSigner.java
/** Copy all the files in a manifest from input to output. */ private static void copyFiles(Manifest manifest, JarFile in, JarArchiveOutputStream out, long timestamp) throws IOException { final byte[] buffer = new byte[4096]; int num;/*ww w.j av a 2 s . c om*/ final Map<String, Attributes> entries = manifest.getEntries(); final List<String> names = new ArrayList<>(entries.keySet()); Collections.sort(names); for (final String name : names) { final JarEntry inEntry = in.getJarEntry(name); if (inEntry.getMethod() == JarArchiveEntry.STORED) { // Preserve the STORED method of the input entry. out.putArchiveEntry(new JarArchiveEntry(inEntry)); } else { // Create a new entry so that the compressed len is recomputed. final JarArchiveEntry je = new JarArchiveEntry(name); je.setTime(timestamp); out.putArchiveEntry(je); } final InputStream data = in.getInputStream(inEntry); while ((num = data.read(buffer)) > 0) { out.write(buffer, 0, num); } out.flush(); out.closeArchiveEntry(); } }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
private static String getManifest(JarFile jar) throws IOException { JarEntry manifestEntry = jar.getJarEntry(MANIFEST_LOCATION); InputStream jis = null;//from w w w. ja va2s. c o m ByteArrayOutputStream baos = null; try { jis = jar.getInputStream(manifestEntry); baos = new ByteArrayOutputStream(); CopyUtil.copyClose(jis, baos); baos.close(); String manifest = baos.toString(); return manifest; } finally { IOUtils.closeQuietly(jis); IOUtils.closeQuietly(baos); } }
From source file:fr.husta.test.assembly.JarWithDependenciesTest.java
@Test public void checkMetaInfContent() throws IOException { // check META-INF/services/java.sql.Driver exists JarFile jar = new JarFile("target/issue-mvn-assembly-plugin-730-jar-with-dependencies.jar"); JarEntry entry = jar.getJarEntry("META-INF/services/java.sql.Driver"); if (entry == null) { fail("the file 'META-INF/services/java.sql.Driver' should exist in jar-with-dependencies"); }/* www.j a v a2s. com*/ // Content should be "org.postgresql.Driver" InputStream is = jar.getInputStream(entry); String content = IOUtils.toString(is, "UTF-8"); System.out.println("JDBC Driver found : " + content.substring(0, content.indexOf("\n"))); assertEquals("org.postgresql.Driver", content.substring(0, content.indexOf("\n"))); // if test fails and content == "sun.jdbc.odbc.JdbcOdbcDriver", // it means it comes from jre/lib/resources.jar!/META-INF/services/java.sql.Driver (which is unwanted) }
From source file:com.dragome.compiler.utils.FileManager.java
public FileObject getFileForInput(String relativeName) { for (Object o : path) { if (o instanceof JarFile) { JarFile jarFile = (JarFile) o; JarEntry entry = jarFile.getJarEntry(relativeName); if (entry != null) { return new FileObject(jarFile, entry); }// w w w . ja va 2 s. com } else { File file = new File(((File) o), relativeName); if (file.exists()) { return new FileObject(file); } } } throw new RuntimeException("Could not find " + relativeName + " on class path"); }
From source file:framework.JarResourceStore.java
public synchronized byte[] read(String pResourceName) { JarFile jar = null; try {// w w w .j a va2 s . c om jar = new JarFile(URLDecoder.decode(filename, "utf-8")); JarEntry jarEntry = jar.getJarEntry(pResourceName); if (jarEntry != null) { InputStream inputStream = jar.getInputStream(jarEntry); try { return IOUtils.toByteArray(inputStream); } finally { inputStream.close(); } } } catch (IOException e) { Loggers.RELOADER.error(e.getMessage(), e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e2) { Loggers.RELOADER.error(e2.getMessage(), e2); } } } return null; }