Example usage for java.util.jar Manifest write

List of usage examples for java.util.jar Manifest write

Introduction

In this page you can find the example usage for java.util.jar Manifest write.

Prototype

public void write(OutputStream out) throws IOException 

Source Link

Document

Writes the Manifest to the specified OutputStream.

Usage

From source file:com.liferay.arquillian.maven.internal.LiferayWarPackagingProcessor.java

/**
 * (non-Javadoc)//from w  ww  .jav  a  2  s .co m
 * @see
 * org.jboss.shrinkwrap.resolver.spi.maven.archive.packaging.PackagingProcessor
 * #importBuildOutput(org.jboss.shrinkwrap.resolver.api.maven.strategy.
 * MavenResolutionStrategy)
 */
@Override
public LiferayWarPackagingProcessor importBuildOutput(MavenResolutionStrategy strategy) {

    log.debug("Building Liferay Plugin Archive");

    ParsedPomFile pomFile = session.getParsedPomFile();

    // Compile and add Java classes

    if (Validate.isReadable(pomFile.getSourceDirectory())) {
        compile(pomFile.getSourceDirectory(), pomFile.getBuildOutputDirectory(), ScopeType.COMPILE,
                ScopeType.RUNTIME, ScopeType.SYSTEM, ScopeType.IMPORT, ScopeType.PROVIDED);
        JavaArchive classes = ShrinkWrap.create(ExplodedImporter.class, "webinf_clases.jar")
                .importDirectory(pomFile.getBuildOutputDirectory()).as(JavaArchive.class);

        archive = archive.merge(classes, ArchivePaths.create("WEB-INF/classes"));

        // Raise bug with shrink wrap ?Since configure creates the base war
        // in target classes, we need to delete from the archive

        log.trace("Removing temp file: " + pomFile.getFinalName() + " form archive");
        archive.delete(ArchivePaths.create("WEB-INF/classes", pomFile.getFinalName()));
    }

    // Add Resources

    for (Resource resource : pomFile.getResources()) {
        archive.addAsResource(resource.getSource(), resource.getTargetPath());
    }

    // Webapp build

    WarPluginConfiguration warPluginConfiguration = new WarPluginConfiguration(pomFile);

    if (Validate.isReadable(warPluginConfiguration.getWarSourceDirectory())) {

        WebArchive webapp = ShrinkWrap.create(ExplodedImporter.class, "webapp.war")
                .importDirectory(warPluginConfiguration.getWarSourceDirectory(),
                        applyFilter(warPluginConfiguration))
                .as(WebArchive.class);

        archive.merge(webapp);
    }

    // Add manifest

    try {
        Manifest manifest = warPluginConfiguration.getArchiveConfiguration().asManifest();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        manifest.write(bout);

        archive.setManifest(new StringAsset(bout.toString()));
    } catch (MavenImporterException e) {
        log.error("Error adding manifest", e);
    } catch (IOException e) {
        log.error("Error adding manifest", e);
    }

    // add dependencies

    this.session = AddAllDeclaredDependenciesTask.INSTANCE.execute(session);

    final Collection<MavenResolvedArtifact> artifacts = session.resolveDependencies(strategy);

    for (MavenResolvedArtifact artifact : artifacts) {
        archive.addAsLibrary(artifact.asFile());
    }

    // Archive Filtering

    archive = ArchiveFilteringUtils.filterArchiveContent(archive, WebArchive.class,
            warPluginConfiguration.getIncludes(), warPluginConfiguration.getExcludes());

    // Liferay Plugin Deployer

    LiferayPluginConfiguration liferayPluginConfiguration = new LiferayPluginConfiguration(pomFile);

    // Temp Archive for processing by Liferay deployers

    String baseDirPath = liferayPluginConfiguration.getBaseDir();

    File tempDestFile = new File(baseDirPath, pomFile.getFinalName());

    File baseDir = new File(baseDirPath);

    if (!baseDir.exists()) {
        baseDir.mkdirs();

        log.info("Created dir " + baseDir);
    }

    log.trace("Temp Archive:" + tempDestFile.getName());

    archive.as(ZipExporter.class).exportTo(tempDestFile, true);

    FileUtils.deleteQuietly(new File(pomFile.getFinalName()));

    if ("hook".equals(liferayPluginConfiguration.getPluginType())) {

        // perform hook deployer task

        HookDeployerTask.INSTANCE.execute(session);
    } else {

        // default is always portletdeployer

        PortletDeployerTask.INSTANCE.execute(session);
    }

    // Call Liferay Deployer

    LiferayPluginConfiguration configuration = new LiferayPluginConfiguration(pomFile);

    File ddPluginArchiveFile = new File(configuration.getDestDir(), pomFile.getArtifactId() + ".war");
    archive = ShrinkWrap.create(ZipImporter.class, pomFile.getFinalName()).importFrom(ddPluginArchiveFile)
            .as(WebArchive.class);

    try {
        FileUtils.forceDelete(ddPluginArchiveFile);

        FileUtils.forceDelete(new File(configuration.getBaseDir(), pomFile.getFinalName()));
    } catch (IOException e) {

        // nothing to do

    }

    return this;
}

From source file:ch.ivyteam.ivy.maven.util.ClasspathJar.java

private void writeManifest(String name, ZipOutputStream jarStream, List<String> classpathEntries)
        throws IOException {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Name", name);
    if (mainClass != null) {
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
    }/*from w  w  w .  j  av  a2 s .  c o m*/
    if (!classpathEntries.isEmpty()) {
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(classpathEntries, " "));
    }
    jarStream.putNextEntry(new ZipEntry(MANIFEST_MF));
    manifest.write(jarStream);
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);
    }//ww  w  .  j av a2s .c  o m

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), Paths.get("output.jar"),
            ImmutableSet.of(Paths.get("input.jar")), /* main class */ null, Paths.get("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context));

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.PackageHelper.java

/**
 *
 *///from   w  ww  .j  av  a2s  . c o  m
protected void generateManifest() {
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    attributes.put(Attributes.Name.MAIN_CLASS, mainClass);
    //This is a typical situation when application is launched with custom launcher
    if (mainVerticle != null) {
        attributes.put(MAIN_VERTICLE, mainVerticle);
    }

    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        manifest.write(bout);
        bout.close();
        byte[] bytes = bout.toByteArray();
        //TODO: merge existing manifest with current one
        this.archive.setManifest(new ByteArrayAsset(bytes));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);
    }/*  ww  w  .  j a  v a  2s.  c  om*/

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(Paths.get("input.jar")), /* main class */ null, tmp.resolve("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context).getExitCode());

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();/*from  ww w  .j av a 2 s.c  o m*/

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

/**
 * From the constructor of {@link JarInputStream}:
 * <p>/*ww w  .  ja  v  a2s  .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.facebook.buck.jvm.java.JarDirectoryStepTest.java

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();//  w  w w .j  ava2 s. c  om

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java

public void initializeRuntimeMetadata(AbstractNeo4jRuntimeInstaller installer, IPath path) {
    File dirFile = path.toFile();
    File manifestFile = path.append(META_INF).append(MANIFEST_MF).toFile();
    FileOutputStream outputStream = null;
    try {// w w  w .  j a  va  2 s . co m
        FileUtils.forceMkdir(manifestFile.getParentFile());
        outputStream = new FileOutputStream(manifestFile);
        Manifest manifest = new Manifest();
        Attributes atts = manifest.getMainAttributes();
        atts.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        atts.putValue(BUNDLE_MANIFEST_VERSION, "2");
        atts.putValue(BUNDLE_NAME, installer.getName());
        atts.putValue(BUNDLE_SYMBOLIC_NAME, installer.getId());
        atts.putValue(BUNDLE_VERSION, installer.getVersion());
        atts.putValue(BUNDLE_CLASS_PATH, buildJarFilesList(dirFile));
        atts.putValue(EXPORT_PACKAGE, buildPackagesList(dirFile));
        manifest.write(outputStream);
        load();
    } catch (Exception e) {
        Logger.log(Logger.SEVERITY_ERROR, e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifest.java

private void updateManifest(String symbolicName, String classPath, String bundleActivator) throws IOException {
    try (FileInputStream manifestInputStream = new FileInputStream(manifestLocation)) {
        Manifest manifest = new Manifest(manifestInputStream);
        Attributes mainAttributes = manifest.getMainAttributes();

        if (mainAttributes.containsKey(new Attributes.Name(BUNDLE_SYMBOLICNAME))) {
            descriptor.markAsInvalid(Arrays.asList(
                    "Plugin JAR is invalid. MANIFEST.MF already contains header: " + BUNDLE_SYMBOLICNAME),
                    null);//from   w w  w.j a  va  2 s .c o  m
            return;
        }
        mainAttributes.put(new Attributes.Name(BUNDLE_SYMBOLICNAME), symbolicName);
        mainAttributes.put(new Attributes.Name(BUNDLE_CLASSPATH), classPath);
        mainAttributes.put(new Attributes.Name(BUNDLE_ACTIVATOR), bundleActivator);

        descriptor.updateBundleInformation(symbolicName, classPath, bundleActivator);

        try (FileOutputStream manifestOutputStream = new FileOutputStream(manifestLocation)) {
            manifest.write(manifestOutputStream);
        }
    }
}