Example usage for java.util.jar Manifest Manifest

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

Introduction

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

Prototype

public Manifest() 

Source Link

Document

Constructs a new, empty Manifest.

Usage

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);//w w w  .  ja va  2s.  com
    }

    // 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:org.jboss.as.test.manualmode.layered.LayeredDistributionTestCase.java

private void buildProductModule(String layer) throws Exception {
    File layerDir = new File(layersDir, layer);
    File moduleDir = new File(layerDir, "org" + File.separator + "jboss" + File.separator + "as"
            + File.separator + "product" + File.separator + "test");
    Assert.assertTrue(moduleDir.mkdirs());
    File moduleXmlFile = new File(moduleDir, "module.xml");
    FileUtils.copyInputStreamToFile(/*  www .  j a  v a2s  . c om*/
            LayeredDistributionTestCase.class.getResourceAsStream("/layered/product-module.xml"),
            moduleXmlFile);

    File manifestDir = new File(moduleDir, "classes" + File.separator + "META-INF");
    Assert.assertTrue(manifestDir.mkdirs());

    File moduleManifestFile = new File(manifestDir, "MANIFEST.MF");
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().putValue("JBoss-Product-Release-Name", PRODUCT_NAME);
    m.getMainAttributes().putValue("JBoss-Product-Release-Version", PRODUCT_VERSION);
    OutputStream manifestStream = new BufferedOutputStream(new FileOutputStream(moduleManifestFile));
    m.write(manifestStream);
    manifestStream.flush();
    manifestStream.close();

    // set product.conf        
    File binDir = new File(AS_PATH, "bin");
    Assert.assertTrue(binDir.exists());
    File productConf = new File(binDir, "product.conf");
    if (productConf.exists())
        productConf.delete();
    FileUtils.writeStringToFile(productConf, "slot=test" + System.getProperty("line.separator"));

}

From source file:org.apache.sling.ide.test.impl.helpers.ProjectAdapter.java

public void createOsgiBundleManifest(OsgiBundleManifest osgiManifest) throws CoreException, IOException {

    Manifest m = new Manifest();
    for (Map.Entry<String, String> entry : osgiManifest.getAttributes().entrySet()) {
        m.getMainAttributes().putValue(entry.getKey(), entry.getValue());
    }/*from  w w w.  j a  v a  2 s .  c o  m*/

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    m.write(out);

    createOrUpdateFile(Path.fromPortableString("src/META-INF/MANIFEST.MF"),
            new ByteArrayInputStream(out.toByteArray()));
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private static List<String> createClasspathJar(File dir, String jarName, List<String> manifestClasspath)
        throws IOException {
    List<String> classpathArgs = new ArrayList<String>();
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(manifestClasspath, ' '));
    File classpathJar = new File(dir, jarName);
    classpathJar.deleteOnExit();/*from w w w.  j a  v a 2  s .  co  m*/
    try (JarOutputStream stream = new JarOutputStream(new FileOutputStream(classpathJar), manifest)) {
    }
    classpathArgs.add("-classpath");
    classpathArgs.add(classpathJar.getCanonicalPath());
    return classpathArgs;
}

From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java

private Manifest createSignatureFile(Manifest manifest) throws IOException {
    byte[] mfRawBytes;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        manifest.write(baos);/*from   ww w  .j a  va  2s  .  com*/
        mfRawBytes = baos.toByteArray();
    }

    Manifest sf = new Manifest();
    Attributes sfMain = sf.getMainAttributes();
    Map<String, Attributes> sfEntries = sf.getEntries();

    sfMain.put(Attributes.Name.SIGNATURE_VERSION, "1.0");
    sfMain.putValue("Created-By", "Apache Felix DeploymentPackageBuilder");
    sfMain.putValue(m_digestAlg + "-Digest-Manifest", calculateDigest(mfRawBytes));
    sfMain.putValue(m_digestAlg + "-Digest-Manifest-Main-Attribute",
            calculateDigest(getRawBytesMainAttributes(manifest)));

    for (Entry<String, Attributes> entry : manifest.getEntries().entrySet()) {
        String name = entry.getKey();
        byte[] entryData = getRawBytesAttributes(entry.getValue());

        sfEntries.put(name, getDigestAttributes(entryData));
    }
    return sf;
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void createJar(String jarName, String folderName, String outputPath) throws IOException {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    JarOutputStream target = new JarOutputStream(new FileOutputStream(outputPath + File.separator + jarName),
            manifest);//from  w w  w  .j  av a  2 s.  c o m
    add(new File(folderName), target);
    target.close();
}

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);
    }//from w w w .  j a v  a  2s . co 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:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java

@Test
public void testLoadClassInOsgiWhiteListWithInvalidBundlePresent() throws Exception {
    String bundlePath = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH;
    String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    String classname = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_SIMPLE_ENTITY;

    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), bundlePath);

    mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build();
    Bundle bundle = installBundle(mgmt, bundleUrl);

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream target = new JarOutputStream(buffer, manifest);
    target.close();//from ww w  .j  av a 2  s. com

    OsgiManager osgiManager = ((ManagementContextInternal) mgmt).getOsgiManager().get();
    Framework framework = osgiManager.getFramework();
    Bundle installedBundle = framework.getBundleContext().installBundle("stream://invalid",
            new ByteArrayInputStream(buffer.toByteArray()));
    assertNotNull(installedBundle);

    Class<?> clazz = bundle.loadClass(classname);
    Entity entity = createSimpleEntity(bundleUrl, clazz);

    String whileList = bundle.getSymbolicName() + ":" + bundle.getVersion();
    System.setProperty(ClassLoaderUtils.WHITE_LIST_KEY, whileList);

    ClassLoaderUtils cluMgmt = new ClassLoaderUtils(getClass(), mgmt);
    ClassLoaderUtils cluClass = new ClassLoaderUtils(clazz);
    ClassLoaderUtils cluEntity = new ClassLoaderUtils(getClass(), entity);

    assertLoadSucceeds(classname, clazz, cluMgmt, cluClass, cluEntity);
    assertLoadSucceeds(bundle.getSymbolicName() + ":" + classname, clazz, cluMgmt, cluClass, cluEntity);
}

From source file:org.apache.brooklyn.rest.resources.CatalogResource.java

@Override
@Beta//from w  ww.  ja v  a2 s . c  om
public Response createFromArchive(byte[] zipInput) {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.ROOT, null)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to add catalog item",
                Entitlements.getEntitlementContext().user());
    }

    BundleMaker bm = new BundleMaker(mgmtInternal());
    File f = null, f2 = null;
    try {
        f = Os.newTempFile("brooklyn-posted-archive", "zip");
        try {
            Files.write(zipInput, f);
        } catch (IOException e) {
            Exceptions.propagate(e);
        }

        ZipFile zf;
        try {
            zf = new ZipFile(f);
        } catch (IOException e) {
            throw new IllegalArgumentException("Invalid ZIP/JAR archive: " + e);
        }
        ZipArchiveEntry bom = zf.getEntry("catalog.bom");
        if (bom == null) {
            bom = zf.getEntry("/catalog.bom");
        }
        if (bom == null) {
            throw new IllegalArgumentException("Archive must contain a catalog.bom file in the root");
        }
        String bomS;
        try {
            bomS = Streams.readFullyString(zf.getInputStream(bom));
        } catch (IOException e) {
            throw new IllegalArgumentException("Error reading catalog.bom from ZIP/JAR archive: " + e);
        }

        try {
            zf.close();
        } catch (IOException e) {
            log.debug("Swallowed exception closing zipfile. Full error logged at trace: {}", e.getMessage());
            log.trace("Exception closing zipfile", e);
        }

        VersionedName vn = BasicBrooklynCatalog.getVersionedName(BasicBrooklynCatalog.getCatalogMetadata(bomS));

        Manifest mf = bm.getManifest(f);
        if (mf == null) {
            mf = new Manifest();
        }
        String bundleNameInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        if (Strings.isNonBlank(bundleNameInMF)) {
            if (!bundleNameInMF.equals(vn.getSymbolicName())) {
                throw new IllegalArgumentException("JAR MANIFEST symbolic-name '" + bundleNameInMF
                        + "' does not match '" + vn.getSymbolicName() + "' defined in BOM");
            }
        } else {
            bundleNameInMF = vn.getSymbolicName();
            mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, bundleNameInMF);
        }

        String bundleVersionInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
        if (Strings.isNonBlank(bundleVersionInMF)) {
            if (!bundleVersionInMF.equals(vn.getVersion().toString())) {
                throw new IllegalArgumentException("JAR MANIFEST version '" + bundleVersionInMF
                        + "' does not match '" + vn.getVersion() + "' defined in BOM");
            }
        } else {
            bundleVersionInMF = vn.getVersion().toString();
            mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, bundleVersionInMF);
        }
        if (mf.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION) == null) {
            mf.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
        }

        f2 = bm.copyAddingManifest(f, mf);

        BasicManagedBundle bundleMetadata = new BasicManagedBundle(bundleNameInMF, bundleVersionInMF, null);
        Bundle bundle;
        try (FileInputStream f2in = new FileInputStream(f2)) {
            bundle = ((ManagementContextInternal) mgmt()).getOsgiManager().get()
                    .installUploadedBundle(bundleMetadata, f2in, false);
        } catch (Exception e) {
            throw Exceptions.propagate(e);
        }

        Iterable<? extends CatalogItem<?, ?>> catalogItems = MutableList
                .copyOf(((ManagementContextInternal) mgmt()).getOsgiManager().get().loadCatalogBom(bundle));

        return buildCreateResponse(catalogItems);
    } catch (RuntimeException ex) {
        throw WebResourceUtils.badRequest(ex);
    } finally {
        if (f != null)
            f.delete();
        if (f2 != null)
            f2.delete();
    }
}

From source file:de.cologneintelligence.fitgoodies.maven.FitIntegrationTestMojo.java

public File writeBootJar(String classpath) throws IOException {
    File bootJar = new File(outputDirectory, "boot.jar");

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, classpath);

    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(bootJar), manifest);
    jarOutputStream.close();/*from  w  ww.j  av a  2s. c o  m*/

    return bootJar;
}