List of usage examples for java.util.jar JarFile MANIFEST_NAME
String MANIFEST_NAME
To view the source code for java.util.jar JarFile MANIFEST_NAME.
Click Source Link
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 ww w . java 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:com.android.build.gradle.internal.transforms.ExtractJarsTransform.java
/** * Provides an {@link Action} for the archive entry. * @param archivePath the archive entry path in the archive. * @param extractCode whether to extract class files * @return the action to implement./*from www . ja v a2s.co m*/ */ @NonNull public static Action getAction(@NonNull String archivePath, boolean extractCode) { // Manifest files are never merged. if (JarFile.MANIFEST_NAME.equals(archivePath)) { return Action.IGNORE; } // split the path into segments. String[] segments = archivePath.split("/"); // empty path? skip to next entry. if (segments.length == 0) { return Action.IGNORE; } return PackagingUtils.checkFileForApkPackaging(archivePath, extractCode) ? Action.COPY : Action.IGNORE; }
From source file:com.jrummyapps.busybox.signing.ZipSigner.java
/** Add the SHA1 of every file to the manifest, creating it if necessary. */ private static Manifest addDigestsToManifest(final JarFile jar) throws IOException, GeneralSecurityException { final Manifest input = jar.getManifest(); final Manifest output = new Manifest(); final Attributes main = output.getMainAttributes(); main.putValue("Manifest-Version", MANIFEST_VERSION); main.putValue("Created-By", CREATED_BY); // We sort the input entries by name, and add them to the output manifest in sorted order. // We expect that the output map will be deterministic. final TreeMap<String, JarEntry> byName = new TreeMap<>(); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); byName.put(entry.getName(), entry); }// w w w .ja v a2 s.c o m final MessageDigest md = MessageDigest.getInstance("SHA1"); final byte[] buffer = new byte[4096]; int num; for (JarEntry entry : byName.values()) { final String name = entry.getName(); if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME) && !name.equals(CERT_RSA_NAME)) { InputStream data = jar.getInputStream(entry); while ((num = data.read(buffer)) > 0) { md.update(buffer, 0, num); } Attributes attr = null; if (input != null) { attr = input.getAttributes(name); } attr = attr != null ? new Attributes(attr) : new Attributes(); attr.putValue("SHA1-Digest", base64encode(md.digest())); output.getEntries().put(name, attr); } } return output; }
From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java
protected void scanArtifactsManifests(Predicate<Pair<URL, Manifest>> manifestHandler) { ClassLoader loader = ExtendedClassUtils.getDefaultClassLoader(getClass()); try {/* ww w .jav a2s. c om*/ for (Enumeration<URL> manifests = loader.getResources(JarFile.MANIFEST_NAME); (manifests != null) && manifests.hasMoreElements();) { URL url = manifests.nextElement(); try { Manifest manifest = ManifestUtils.loadManifest(url); if (manifestHandler.evaluate(Pair.of(url, manifest))) { logger.info("Scanning stopped by handler at URL=" + url.toExternalForm()); break; } } catch (Exception e) { logger.warn(e.getClass().getSimpleName() + " while handle URL=" + url.toExternalForm() + ": " + e.getMessage()); } } } catch (IOException e) { logger.warn("Failed (" + e.getClass().getSimpleName() + ") to get manifests URLs: " + e.getMessage()); } }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
/** * From the constructor of {@link JarInputStream}: * <p>/*w ww. ja va 2s . c o m*/ * This implementation assumes the META-INF/MANIFEST.MF entry * should be either the first or the second entry (when preceded * by the dir META-INF/). It skips the META-INF/ and then * "consumes" the MANIFEST.MF to initialize the Manifest object. * <p> * A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be * included, adding them to the output jar, while merging manifest files, writing the merged * manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't * be able to find the manifest for. */ @Test public void manifestShouldBeSecondEntryInJar() throws IOException { Path manifestPath = Paths.get(JarFile.MANIFEST_NAME); // Create a directory with a manifest in it and more than two files. Path dir = folder.newFolder(); Manifest dirManifest = new Manifest(); Attributes attrs = new Attributes(); attrs.putValue("From-Dir", "cheese"); dirManifest.getEntries().put("Section", attrs); Files.createDirectories(dir.resolve(manifestPath).getParent()); try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) { dirManifest.write(out); } Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8)); Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8)); Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8)); Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8)); // Create a jar with a manifest and more than two other files. Path inputJar = folder.newFile("example.jar"); try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) { byte[] data = "hello world".getBytes(UTF_8); ZipEntry entry = new ZipEntry("C.txt"); zos.putNextEntry(entry); zos.write(data, 0, data.length); zos.closeEntry(); entry = new ZipEntry("cc.txt"); zos.putNextEntry(entry); zos.write(data, 0, data.length); zos.closeEntry(); entry = new ZipEntry("META-INF/"); zos.putNextEntry(entry); zos.closeEntry(); // Note: at end of the stream. Technically invalid. entry = new ZipEntry(JarFile.MANIFEST_NAME); zos.putNextEntry(entry); Manifest zipManifest = new Manifest(); attrs = new Attributes(); attrs.putValue("From-Zip", "peas"); zipManifest.getEntries().put("Section", attrs); zipManifest.write(zos); zos.closeEntry(); } // Merge and check that the manifest includes everything Path output = folder.newFile("output.jar"); JarDirectoryStep step = new JarDirectoryStep(new FakeProjectFilesystem(folder.getRoot()), output, ImmutableSortedSet.of(dir, inputJar), null, null); int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode(); assertEquals(0, exitCode); Manifest manifest; try (InputStream is = Files.newInputStream(output); JarInputStream jis = new JarInputStream(is)) { manifest = jis.getManifest(); } assertNotNull(manifest); Attributes readAttributes = manifest.getAttributes("Section"); assertEquals(2, readAttributes.size()); assertEquals("cheese", readAttributes.getValue("From-Dir")); assertEquals("peas", readAttributes.getValue("From-Zip")); }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Closes the Jar archive by creating the manifest, and signing the archive. * * @throws IOException//w w w. j a v a2s.com * @throws SigningException */ public void close() throws IOException, SigningException { if (mManifest != null) { // write the manifest to the jar file mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME)); mManifest.write(mOutputJar); try { // CERT.SF Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm()); signature.initSign(mKey); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF")); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF")); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeSignatureFile(baos); byte[] signedData = baos.toByteArray(); mOutputJar.write(signedData); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm())); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + "." + mKey.getAlgorithm())); } // CERT.* writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey); } catch (Exception e) { throw new SigningException(e); } } mOutputJar.close(); mOutputJar = null; }
From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java
/** * Create a jar file from the given directory. * @param dir source directory//from ww w.j a v a 2 s. c om * @param jarFile jar file name * @throws IOException when file cannot be created */ public static void createJar(File dir, File jarFile) throws IOException { final Map<String, ?> env = Collections.singletonMap("create", "true"); if (jarFile.exists() && !jarFile.delete()) { throw new RuntimeException("Failed to remove " + jarFile); } URI uri = URI.create("jar:" + jarFile.toURI()); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { File manifestFile = new File(dir, JarFile.MANIFEST_NAME); Files.createDirectory(zipfs.getPath("META-INF")); try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) { if (!manifestFile.exists()) { new Manifest().write(out); } else { FileUtils.copyFile(manifestFile, out); } } final java.nio.file.Path root = dir.toPath(); Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() { String relativePath; @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { relativePath = root.relativize(dir).toString(); if (!relativePath.isEmpty()) { if (!relativePath.endsWith("/")) { relativePath += "/"; } if (!relativePath.equals("META-INF/")) { final Path dstDir = zipfs.getPath(relativePath); Files.createDirectory(dstDir); } } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String name = relativePath + file.getFileName(); if (!JarFile.MANIFEST_NAME.equals(name)) { try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) { FileUtils.copyFile(file.toFile(), out); } } return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { relativePath = root.relativize(dir.getParent()).toString(); if (!relativePath.isEmpty() && !relativePath.endsWith("/")) { relativePath += "/"; } return super.postVisitDirectory(dir, exc); } }); } }
From source file:org.apache.beam.runners.apex.ApexYarnLauncherTest.java
@Test public void testCreateJar() throws Exception { File baseDir = new File("./target/testCreateJar"); File srcDir = new File(baseDir, "src"); String file1 = "file1"; FileUtils.forceMkdir(srcDir);// www . ja va 2 s . c om FileUtils.write(new File(srcDir, file1), "file1"); File jarFile = new File(baseDir, "test.jar"); ApexYarnLauncher.createJar(srcDir, jarFile); Assert.assertTrue("exists: " + jarFile, jarFile.exists()); URI uri = URI.create("jar:" + jarFile.toURI()); final Map<String, ?> env = Collections.singletonMap("create", "true"); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env);) { Assert.assertTrue("manifest", Files.isRegularFile(zipfs.getPath(JarFile.MANIFEST_NAME))); Assert.assertTrue("file1", Files.isRegularFile(zipfs.getPath(file1))); } }
From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java
public void writeSignedManifest(Manifest manifest, ZipOutputStream zos, PrivateKey privKey, X509Certificate cert) throws Exception { zos.putNextEntry(new ZipEntry(JarFile.MANIFEST_NAME)); manifest.write(zos);/* w ww.j a v a 2 s .co m*/ zos.closeEntry(); long now = System.currentTimeMillis(); // Determine the signature-file manifest... Manifest sf = createSignatureFile(manifest); byte[] sfRawBytes; try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { sf.write(baos); sfRawBytes = baos.toByteArray(); } ZipEntry sigFileEntry = new ZipEntry(m_baseName.concat(".SF")); sigFileEntry.setTime(now); zos.putNextEntry(sigFileEntry); // Write the actual entry data... zos.write(sfRawBytes, 0, sfRawBytes.length); zos.closeEntry(); // Create a PKCS#7 signature... byte[] encoded = calculateSignatureBlock(privKey, cert, sfRawBytes); ZipEntry blockFileEntry = new ZipEntry(m_baseName.concat(getBlockFileExtension(privKey))); blockFileEntry.setTime(now); zos.putNextEntry(blockFileEntry); zos.write(encoded); zos.closeEntry(); }
From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.java
public static void jarDir(File dir, String relativePath, ZipOutputStream zos) throws IOException { Preconditions.checkNotNull(relativePath, "relativePath"); Preconditions.checkNotNull(zos, "zos"); // by JAR spec, if there is a manifest, it must be the first entry in // the/*from www .j a v a2 s.co m*/ // ZIP. File manifestFile = new File(dir, JarFile.MANIFEST_NAME); ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); if (!manifestFile.exists()) { zos.putNextEntry(manifestEntry); new Manifest().write(new BufferedOutputStream(zos)); zos.closeEntry(); } else { InputStream is = new FileInputStream(manifestFile); copyToZipStream(is, manifestEntry, zos); } zos.closeEntry(); zipDir(dir, relativePath, zos, true); zos.close(); }