List of usage examples for java.util.jar Manifest Manifest
public Manifest()
From source file:com.taobao.android.apatch.FastBuild.java
@Override protected Manifest getMeta() { Manifest manifest = new Manifest(); Attributes main = manifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (ApkPatch)"); main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString()); main.putValue("Patch-Name", name); main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes)); main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses)); main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods)); main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses)); main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses)); main.putValue(name + "-add-classes", Formater.dotStringList(addClasses)); return manifest; }
From source file:com.taobao.android.apatch.MergePatch.java
@SuppressWarnings("deprecation") @Override//from w ww .j a va 2s. c o m protected Manifest getMeta() { Manifest retManifest = new Manifest(); Attributes main = retManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (ApkPatch)"); main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString()); main.putValue("Patch-Name", name); try { fillManifest(main); } catch (IOException e) { e.printStackTrace(); return null; } return retManifest; }
From source file:com.jrummyapps.busybox.signing.ZipSigner.java
/** * Write a .SF file with a digest the specified manifest. */// w ww . j a v a2s . c o m private static byte[] writeSignatureFile(Manifest manifest, OutputStream out) throws IOException, GeneralSecurityException { final Manifest sf = new Manifest(); final Attributes main = sf.getMainAttributes(); main.putValue("Manifest-Version", MANIFEST_VERSION); main.putValue("Created-By", CREATED_BY); final MessageDigest md = MessageDigest.getInstance("SHA1"); final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8"); // Digest of the entire manifest manifest.write(print); print.flush(); main.putValue("SHA1-Digest-Manifest", base64encode(md.digest())); final Map<String, Attributes> entries = manifest.getEntries(); for (final Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (final Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); final Attributes sfAttr = new Attributes(); sfAttr.putValue("SHA1-Digest", base64encode(md.digest())); sf.getEntries().put(entry.getKey(), sfAttr); } final ByteArrayOutputStream sos = new ByteArrayOutputStream(); sf.write(sos); String value = sos.toString(); String done = value.replace("Manifest-Version", "Signature-Version"); out.write(done.getBytes()); print.close(); sos.close(); return done.getBytes(); }
From source file:net.cliseau.composer.javacor.MissingToolException.java
/** * Create a JAR file for startup of the unit. * * The created JAR file contains all the specified archive files and contains a * manifest which in particular determines the class path for the JAR file. * All files in startupArchiveFileNames are deleted during the execution of * this method.//from w w w . j av a 2 s.c o m * * @param fileName Name of the file to write the result to. * @param startupArchiveFileNames Names of files to include in the JAR file. * @param startupDependencies Names of classpath entries to include in the JAR file classpath. * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s). */ private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames, final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException { // Code inspired by: // http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm // http://www.massapi.com/class/java/util/jar/Manifest.java.html // construct manifest with appropriate "Class-path" property Manifest starterManifest = new Manifest(); Attributes starterAttributes = starterManifest.getMainAttributes(); // Remark for those who read this code to learn something: // If one forgets to set the MANIFEST_VERSION attribute, then // silently *nothing* (except for a line break) will be written // to the JAR file manifest! starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName()); starterAttributes.put(Attributes.Name.CLASS_PATH, StringUtils.join(startupDependencies, manifestClassPathSeparator)); // create output JAR file FileOutputStream fos = new FileOutputStream(fileName); JarOutputStream jos = new JarOutputStream(fos, starterManifest); // add the entries for the starter archive's files for (String archFileName : startupArchiveFileNames) { File startupArchiveFile = new File(archFileName); JarEntry startupEntry = new JarEntry(startupArchiveFile.getName()); startupEntry.setTime(startupArchiveFile.lastModified()); jos.putNextEntry(startupEntry); // copy the content of the starter archive's file // TODO: if we used Apache Commons IO 2.1, then the following // code block could be simplified as: // FileUtils.copyFile(startupArchiveFile, jos); FileInputStream fis = new FileInputStream(startupArchiveFile); byte buffer[] = new byte[1024 /*bytes*/]; while (true) { int nRead = fis.read(buffer, 0, buffer.length); if (nRead <= 0) break; jos.write(buffer, 0, nRead); } fis.close(); // end of FileUtils.copyFile() substitution code jos.closeEntry(); startupArchiveFile.delete(); // cleanup the disk a bit } jos.close(); fos.close(); }
From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java
private Manifest getManifest() { HashCodeBuilder builder = new HashCodeBuilder(11, 17); for (CodeGenerator gen : getAllCurrentGenerators()) { builder.append(gen.hashForManifest()); }//from w w w .jav a 2 s. co m Manifest manifest = new Manifest(); Attributes mainAttributes = manifest.getMainAttributes(); mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttributes.put(NUCLOS_CODE_NUCLET, "default"); mainAttributes.put(NUCLOS_CODE_HASH, String.valueOf(builder.toHashCode())); return manifest; }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
/** * From the constructor of {@link JarInputStream}: * <p>//from w w w. ja va 2 s . co 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:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java
/** * /* w w w . j a v a2 s . com*/ * create one default index bean which based one the component zip file directly. * * bundleId, version, mvn_uri are required */ public ComponentIndexBean create(File componentZipFile) { if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory() || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) { return null; } String name = null; String bundleId = null; String bundleVersion = null; String mvnUri = null; ZipFile zipFile = null; try { zipFile = new ZipFile(componentZipFile); Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries(); while (enumeration.hasMoreElements()) { final ZipEntry zipEntry = enumeration.nextElement(); String path = zipEntry.getName(); if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar // if it's bundle, not from other folder, like lib, m2 repository. IPath p = new Path(path); // must be in plugins if (p.segmentCount() > 1 && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) { if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) { JarInputStream jarEntryStream = null; try { // must use another stream jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry)); // find the bundleId and version Manifest manifest = jarEntryStream.getManifest(); if (manifest != null) { bundleId = JarMenifestUtil.getBundleSymbolicName(manifest); bundleVersion = JarMenifestUtil.getBundleVersion(manifest); } boolean checkManifest = StringUtils.isBlank(bundleId) || StringUtils.isBlank(bundleVersion); // find the pom.properties JarEntry jarEntry = null; while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) { final String entryPath = jarEntry.getName(); if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) { manifest = new Manifest(); manifest.read(jarEntryStream); bundleId = JarMenifestUtil.getBundleSymbolicName(manifest); bundleVersion = JarMenifestUtil.getBundleVersion(manifest); checkManifest = false; } final Path fullPath = new Path(entryPath); final String fileName = fullPath.lastSegment(); /* * for example, * META-INF/maven/org.talend.components/components-splunk/pom.properties */ if (fileName.equals("pom.properties") //$NON-NLS-1$ && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$ // FIXME, didn't find one way to read the inner jar // final InputStream propStream = jarFile.getInputStream(jarEntry); // if (propStream != null) { // Properties pomProp = new Properties(); // pomProp.load(propStream); // // String version = pomProp.getProperty("version"); //$NON-NLS-1$ // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$ // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$ // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version, // FileExtensions.ZIP_FILE_SUFFIX, null); // // propStream.close(); // } // FIXME, try the path way // META-INF/maven/org.talend.components/components-splunk IPath tmpMavenPath = fullPath.removeLastSegments(1); String artifactId = tmpMavenPath.lastSegment(); // components-splunk // META-INF/maven/org.talend.components tmpMavenPath = tmpMavenPath.removeLastSegments(1); String groupId = tmpMavenPath.lastSegment(); // org.talend.components mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion, FileExtensions.ZIP_EXTENSION, null); } else /* * /OSGI-INF/installer$$splunk.xml */ if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX) && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX) && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) { name = fullPath.removeFileExtension().lastSegment(); name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX) + UpdatesHelper.NEW_COMPONENT_PREFIX.length()); } } } catch (IOException e) { // } finally { try { if (jarEntryStream != null) { jarEntryStream.close(); } } catch (IOException e) { // } } } } } } } catch (ZipException e) { if (CommonsPlugin.isDebugMode()) { ExceptionHandler.process(e); } } catch (IOException e) { if (CommonsPlugin.isDebugMode()) { ExceptionHandler.process(e); } } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // } } } // set the required if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) { final ComponentIndexBean indexBean = new ComponentIndexBean(); final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri); indexBean.setValue(ComponentIndexNames.types, PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0))); if (set) { return indexBean; } } return null; }
From source file:co.cask.cdap.internal.app.services.http.handlers.ArtifactHttpHandlerTest.java
@Test public void testPluginNamespaceIsolation() throws Exception { // add a system artifact. currently can't do this through the rest api (by design) // so bypass it and use the repository directly Id.Artifact systemId = Id.Artifact.from(Id.Namespace.SYSTEM, "wordcount", "1.0.0"); File systemArtifact = buildAppArtifact(WordCountApp.class, "wordcount-1.0.0.jar"); artifactRepository.addArtifact(systemId, systemArtifact, Sets.<ArtifactRange>newHashSet()); Set<ArtifactRange> parents = Sets.newHashSet(new ArtifactRange(systemId.getNamespace(), systemId.getName(), systemId.getVersion(), true, systemId.getVersion(), true)); Id.Namespace namespace1 = Id.Namespace.from("ns1"); Id.Namespace namespace2 = Id.Namespace.from("ns2"); createNamespace(namespace1.getId()); createNamespace(namespace2.getId()); try {// w ww .j a v a2s . com // add some plugins in namespace1. Will contain Plugin1 and Plugin2 Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, Plugin1.class.getPackage().getName()); Id.Artifact pluginsId1 = Id.Artifact.from(namespace1, "plugins1", "1.0.0"); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(pluginsId1, Plugin1.class, manifest, parents).getStatusLine() .getStatusCode()); // add some plugins in namespace2. Will contain Plugin1 and Plugin2 manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, Plugin1.class.getPackage().getName()); Id.Artifact pluginsId2 = Id.Artifact.from(namespace2, "plugins2", "1.0.0"); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(pluginsId2, Plugin1.class, manifest, parents).getStatusLine() .getStatusCode()); ArtifactSummary artifact1 = new ArtifactSummary(pluginsId1.getName(), pluginsId1.getVersion().getVersion(), ArtifactScope.USER); ArtifactSummary artifact2 = new ArtifactSummary(pluginsId2.getName(), pluginsId2.getVersion().getVersion(), ArtifactScope.USER); PluginSummary summary1Namespace1 = new PluginSummary("Plugin1", "dummy", "This is plugin1", Plugin1.class.getName(), artifact1); PluginSummary summary2Namespace1 = new PluginSummary("Plugin2", "callable", "Just returns the configured integer", Plugin2.class.getName(), artifact1); PluginSummary summary1Namespace2 = new PluginSummary("Plugin1", "dummy", "This is plugin1", Plugin1.class.getName(), artifact2); PluginSummary summary2Namespace2 = new PluginSummary("Plugin2", "callable", "Just returns the configured integer", Plugin2.class.getName(), artifact2); PluginInfo info1Namespace1 = new PluginInfo("Plugin1", "dummy", "This is plugin1", Plugin1.class.getName(), artifact1, ImmutableMap.of("x", new PluginPropertyField("x", "", "int", true), "stuff", new PluginPropertyField("stuff", "", "string", true)), new HashSet<String>()); PluginInfo info2Namespace1 = new PluginInfo("Plugin2", "callable", "Just returns the configured integer", Plugin2.class.getName(), artifact1, ImmutableMap.of("v", new PluginPropertyField("v", "value to return when called", "int", true)), new HashSet<String>()); PluginInfo info1Namespace2 = new PluginInfo("Plugin1", "dummy", "This is plugin1", Plugin1.class.getName(), artifact2, ImmutableMap.of("x", new PluginPropertyField("x", "", "int", true), "stuff", new PluginPropertyField("stuff", "", "string", true)), new HashSet<String>()); PluginInfo info2Namespace2 = new PluginInfo("Plugin2", "callable", "Just returns the configured integer", Plugin2.class.getName(), artifact2, ImmutableMap.of("v", new PluginPropertyField("v", "value to return when called", "int", true)), new HashSet<String>()); Id.Artifact namespace1Artifact = Id.Artifact.from(namespace1, systemId.getName(), systemId.getVersion()); Id.Artifact namespace2Artifact = Id.Artifact.from(namespace2, systemId.getName(), systemId.getVersion()); // should see same types in both namespaces Assert.assertEquals(ImmutableSet.of("dummy", "callable"), getPluginTypes(namespace1Artifact, ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of("dummy", "callable"), getPluginTypes(namespace2Artifact, ArtifactScope.SYSTEM)); // should see that plugins in namespace1 come only from the namespace1 artifact Assert.assertEquals(ImmutableSet.of(summary1Namespace1), getPluginSummaries(namespace1Artifact, "dummy", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(summary2Namespace1), getPluginSummaries(namespace1Artifact, "callable", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(info1Namespace1), getPluginInfos(namespace1Artifact, "dummy", "Plugin1", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(info2Namespace1), getPluginInfos(namespace1Artifact, "callable", "Plugin2", ArtifactScope.SYSTEM)); // should see that plugins in namespace2 come only from the namespace2 artifact Assert.assertEquals(ImmutableSet.of(summary1Namespace2), getPluginSummaries(namespace2Artifact, "dummy", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(summary2Namespace2), getPluginSummaries(namespace2Artifact, "callable", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(info1Namespace2), getPluginInfos(namespace2Artifact, "dummy", "Plugin1", ArtifactScope.SYSTEM)); Assert.assertEquals(ImmutableSet.of(info2Namespace2), getPluginInfos(namespace2Artifact, "callable", "Plugin2", ArtifactScope.SYSTEM)); } finally { deleteNamespace("iso1"); deleteNamespace("iso2"); } }
From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java
private File createJar(final String cp, final String mainClass) { try {/* www . java2 s . com*/ Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, cp); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); File tempFile = File.createTempFile("clojuremavenplugin", "jar"); tempFile.deleteOnExit(); JarOutputStream target = new JarOutputStream(new FileOutputStream(tempFile), manifest); target.close(); return tempFile; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java
/** * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable, * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark. * * @param dependencyJar {@link Location} of the job jar to be updated * @param context {@link BasicSparkContext} of this job *///from ww w.j a va 2 s. com private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException { final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB, ApplicationBundler.SUBDIR_RESOURCES }; Id.Program programId = context.getProgram().getId(); Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar", ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(), programId.getId(), context.getRunId().getId())); // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest); try { JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream()); try { JarEntry jarEntry = jarInput.getNextJarEntry(); while (jarEntry != null) { boolean isDir = jarEntry.isDirectory(); String entryName = jarEntry.getName(); String newEntryName = entryName; for (String prefix : prefixToStrip) { if (entryName.startsWith(prefix) && !entryName.equals(prefix)) { newEntryName = entryName.substring(prefix.length()); } } jarEntry = new JarEntry(newEntryName); jarOutput.putNextEntry(jarEntry); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } jarEntry = jarInput.getNextJarEntry(); } } finally { jarInput.close(); Locations.deleteQuietly(dependencyJar); } } finally { jarOutput.close(); } return updatedJar; }