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:io.zatarox.satellite.impl.BackgroundWrapperTest.java

@BeforeClass
public static void setBefore() throws Exception {
    file = File.createTempFile("archive", ".jar");
    file.deleteOnExit();/* w  w  w. j  a va2s .  co m*/
    final FileOutputStream out = new FileOutputStream(file);
    ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
            out);
    ZipArchiveEntry entry = new ZipArchiveEntry("META-INF/MANIFEST.MF");
    archive.putArchiveEntry(entry);
    final Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Background-Process-Class",
            FakeBackgroundProcessImpl.class.getName());
    manifest.write(archive);
    archive.closeArchiveEntry();
    archive.close();
}

From source file:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();/* w  w  w . jav  a  2 s . co  m*/
    }
    if (!dest.isDirectory()) {
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(in);
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    /* Explicity write out the META-INF/MANIFEST.MF so that any headers such
    as the Class-Path are see for the unpackaged jar
    */
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (parent.exists() == false) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        out.close();
    }
    jin.close();
}

From source file:com.jrummyapps.busybox.utils.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys./*from  w  w w.  j  ava2 s  . c o  m*/
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IoUtils.closeQuietly(inputJar);
        IoUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using
 * SHA1 and RSA keys./*from   w ww .j  ava  2  s  . c om*/
 *
 * @param unsignedZip
 *     The path to the APK, ZIP, JAR to sign
 * @param destination
 *     The output file
 * @return true if successfully signed the file
 */
public static boolean signZip(File unsignedZip, File destination) {
    final AssetManager am = App.getContext().getAssets();
    JarArchiveOutputStream outputJar = null;
    JarFile inputJar = null;

    try {
        X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY));
        PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY));

        // Assume the certificate is valid for at least an hour.
        long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;

        inputJar = new JarFile(unsignedZip, false); // Don't verify.
        FileOutputStream stream = new FileOutputStream(destination);
        outputJar = new JarArchiveOutputStream(stream);
        outputJar.setLevel(9);

        // MANIFEST.MF
        Manifest manifest = addDigestsToManifest(inputJar);
        JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        manifest.write(outputJar);

        ZipSignature signature1 = new ZipSignature();
        signature1.initSign(privateKey);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeSignatureFile(manifest, out);

        // CERT.SF
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKey);
        je = new JarArchiveEntry(CERT_SF_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);
        byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));

        signature1.update(sfBytes);
        byte[] signatureBytes = signature1.sign();

        // CERT.RSA
        je = new JarArchiveEntry(CERT_RSA_NAME);
        je.setTime(timestamp);
        outputJar.putArchiveEntry(je);

        outputJar.write(readContentAsBytes(am.open(TEST_KEY)));
        outputJar.write(signatureBytes);

        copyFiles(manifest, inputJar, outputJar, timestamp);
    } catch (Exception e) {
        Crashlytics.logException(e);
        return false;
    } finally {
        IOUtils.closeQuietly(inputJar);
        IOUtils.closeQuietly(outputJar);
    }
    return true;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Write a .SF file with a digest the specified manifest.
 *///  w  ww  . jav  a  2  s .c om
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:com.redhat.rcm.maven.plugin.buildmetadata.util.ManifestHelper.java

/**
 * Creates a Manifest file based on the given properties.
 *
 * @param buildMetaDataProperties the properties to add to the Manifest file
 *          to be written.//  w w w .  ja  va 2  s .  com
 * @throws IOException on any problem writing the file.
 */
public void createManifest(final Properties buildMetaDataProperties) throws IOException {
    final Manifest manifest = createManifestInstance(buildMetaDataProperties);

    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(manifestFile));
        manifest.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java

public InputStream buildJar(final IFolder sourceDir) throws CoreException {

    ByteArrayOutputStream store = new ByteArrayOutputStream();

    JarOutputStream zos = null;/*  www  . j av a 2 s  .c  o m*/
    InputStream manifestInput = null;
    try {
        IResource manifestResource = sourceDir.findMember(JarFile.MANIFEST_NAME);
        if (manifestResource == null || manifestResource.getType() != IResource.FILE) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "No file named " + JarFile.MANIFEST_NAME + " found under " + sourceDir));
        }

        manifestInput = ((IFile) manifestResource).getContents();

        Manifest manifest = new Manifest(manifestInput);

        zos = new JarOutputStream(store);
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        manifest.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(manifestInput);
    }

    return new ByteArrayInputStream(store.toByteArray());
}

From source file:com.npower.dl.SoftwareDownloadServlet.java

public void doDownloadJAD(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestUri = request.getRequestURI();
    log.info("Download Service: Download Content: uri: " + requestUri);
    String requestUrl = request.getRequestURL().toString();

    String packageID = parserPackageID(requestUri);
    ManagementBeanFactory factory = null;
    try {//  ww  w . j a  va 2s.  co  m
        factory = ManagementBeanFactory.newInstance(EngineConfig.getProperties());
        SoftwareBean bean = factory.createSoftwareBean();
        SoftwarePackage pkg = bean.getPackageByID(Long.parseLong(packageID));
        if (pkg == null) {
            throw new DMException("Could not found download package by package ID: " + packageID);
        }
        if (pkg.getMimeType().equalsIgnoreCase("text/vnd.sun.j2me.app-descriptor")) {
            // Content is JAD
            InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream();
            if (pkg.getSize() > 0) {
                response.setContentType(pkg.getMimeType());
                response.setContentLength(pkg.getSize());
                OutputStream out = response.getOutputStream();
                byte[] buf = new byte[1024];
                int len = ins.read(buf);
                while (len > 0) {
                    out.write(buf, 0, len);
                    len = ins.read(buf);
                }
                out.flush();
                //out.close();
                return;
            }
        } else if (pkg.getMimeType().equalsIgnoreCase("application/java-archive")
                || pkg.getMimeType().equalsIgnoreCase("application/java")
                || pkg.getMimeType().equalsIgnoreCase("application/x-java-archive")) {
            // JAR Format, generate a JAD
            File jarFile = File.createTempFile("software_tmp", "jar");
            InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream();
            if (pkg.getSize() > 0) {
                OutputStream out = new FileOutputStream(jarFile);
                byte[] buf = new byte[1024];
                int len = ins.read(buf);
                while (len > 0) {
                    out.write(buf, 0, len);
                    len = ins.read(buf);
                }
                out.flush();
                out.close();

                String url4Jar = StringUtils.replace(requestUrl, ".jad", ".jar");
                JADCreator creator = new JADCreator();
                Manifest manifest = creator.getJADManufest(jarFile, url4Jar);
                response.setContentType(pkg.getMimeType());
                manifest.write(response.getOutputStream());

                // Clean temp file
                jarFile.delete();
                return;
            }
        }
        // Return Not Found Code.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (factory != null) {
            factory.release();
        }
    }
}

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

@Override
public LiferayWarPackagingProcessor importBuildOutput(MavenResolutionStrategy strategy)
        throws IllegalArgumentException, ResolutionException {

    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()));
    }//from   ww w . j av a 2s  .c o m

    // 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);
    }

    // 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:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifestTest.java

private void addHeaderToManifest(String header, String value) throws IOException {
    FileInputStream manifestInputStream = new FileInputStream(manifestFile);
    Manifest manifest = new Manifest(manifestInputStream);
    Attributes entries = manifest.getMainAttributes();
    entries.put(new Attributes.Name(header), value);

    FileOutputStream manifestOutputStream = new FileOutputStream(manifestFile, false);
    manifest.write(manifestOutputStream);
    manifestOutputStream.close();/*from www.  j  a  v a 2  s .com*/
    manifestInputStream.close();
}