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.googlecode.mycontainer.maven.plugin.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for
 * SurefireBooter and a Class-Path entry for all classpath elements. Copied
 * from surefire (ForkConfiguration#createJar())
 * /*from   w  w  w  .  ja v  a  2s.  c  o  m*/
 * @param classPath
 *            List<String> of all classpath elements.
 * @return
 * @throws IOException
 */
private File createJar(List classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    Manifest man = new Manifest();

    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    String cp = "";
    for (Iterator it = classPath.iterator(); it.hasNext();) {
        String el = (String) it.next();
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp += UrlUtils.getURL(new File(el)).toExternalForm() + " ";
    }

    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);

    man.write(jos);
    jos.close();

    return file;
}

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

@Test
public void shouldIncludeUserSuppliedManifestIfProvided() throws IOException {
    setUpProjectWorkspaceForScenario("manifest");

    Manifest m = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("Data", "cheese");
    m.getEntries().put("Example", attrs);
    m.write(System.out);

    Path path = workspace.buildAndReturnOutput("//:library");

    try (InputStream is = Files.newInputStream(path); JarInputStream jis = new JarInputStream(is)) {
        Manifest manifest = jis.getManifest();
        String value = manifest.getEntries().get("Example").getValue("Data");
        assertEquals("cheese", value);
    }//from  w ww.  ja v  a2  s.  c om
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List<String> of all classpath elements.
 * @return//from   ww  w . jav a2s . c om
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);
    Manifest man = new Manifest();
    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }
    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);
    man.write(jos);
    jos.close();
    return file;
}

From source file:kr.motd.maven.exec.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List&lt;String> of all classpath elements.
 * @return/*from   w w  w.j  av  a 2s  .co m*/
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    Manifest man = new Manifest();

    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }

    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);

    man.write(jos);
    jos.close();

    return file;
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * This method copies contents of target/classes to target/test-classes.
 * Thanks to that regular classes of given bundle can be used for testing
 * without a need to load the bundle from maven repository. It is very
 * important because in the maven build cycle "test" precedes "install". If
 * this method will not be invoked, when bundle does not exist in the maven
 * repository there is a deadlock - bundle cannot be tested because it is
 * not in the repo and bundle cannot be installed in the repo because tests
 * fail.//from   w w w.  ja  v a 2 s  . c  om
 *
 * Additionally method rewrites bundle manifest for purpose of adding
 * imports to packages related to itests bundle.
 *
 * @throws IOException
 *
 */
private void prepareClassesToTests() throws Exception {
    FileUtils.copyDirectory(new File("./target/classes"), new File("./target/test-classes"));
    File separatedArtifactDepsFile = new File(IntegrationTestConsts.SEPARATED_ARTIFACT_DEPS);
    if (separatedArtifactDepsFile.exists()) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(separatedArtifactDepsFile)));
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (!line.isEmpty()) {
                unzipInpuStream(new URL(line).openStream(), "target/test-classes");
            }
        }
    }

    Manifest bundleMf = new Manifest(new FileInputStream("./target/classes/META-INF/MANIFEST.MF"));
    Attributes mainAttribs = bundleMf.getMainAttributes();

    bundleSymbolicName = mainAttribs.getValue("Bundle-SymbolicName");
    bundleVersion = mainAttribs.getValue("Bundle-Version");
    bundleVersion = bundleVersion.replaceFirst("\\.SNAPSHOT", "-SNAPSHOT");

    mainAttribs.put(new Attributes.Name("Import-Package"),
            mainAttribs.getValue("Import-Package") + ",org.universAAL.itests,org.springframework.util");
    String dynamicImports = mainAttribs.getValue("DynamicImport-Package");
    if (dynamicImports == null) {
        dynamicImports = "*";
        mainAttribs.put(new Attributes.Name("DynamicImport-Package"), dynamicImports);
    }

    bundleMf.write(new FileOutputStream("./target/test-classes/META-INF/MANIFEST.MF"));
}

From source file:com.orange.mmp.widget.WidgetManager.java

/**
 * Add branch ID to a widget Manifest before deploying it
 * @param widgetFile//  w  w w. j ava2s.  c  om
 * @param branchId
 * @return a Widget instance
 * @throws IOException 
 * @throws MMPException 
 */
public Widget deployWidget(File widgetFile, String branchId) throws MMPException {
    Widget widget = new Widget();
    ZipInputStream zin = null;
    ZipOutputStream zout = null;

    try {
        JarFile jarFile = new JarFile(new File(widgetFile.toURI()));
        Manifest manifest = jarFile.getManifest();

        String tmpWidgetId = manifest.getMainAttributes()
                .getValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER);
        widget.setBranchId(branchId);

        if (tmpWidgetId != null) {
            widget.setName(manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_NAME_HEADER));
            widget.setId(tmpWidgetId + com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN + branchId);
            manifest.getMainAttributes().putValue(FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER,
                    widget.getId());

            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".jar");

            zin = new ZipInputStream(new FileInputStream(widgetFile));
            zout = new ZipOutputStream(new FileOutputStream(tempFile));

            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                zout.putNextEntry(new ZipEntry(name));
                if (!name.equals(com.orange.mmp.midlet.Constants.JAR_MANIFEST_ENTRY)) {
                    IOUtils.copy(zin, zout);
                } else {
                    manifest.write(zout);
                }
                entry = zin.getNextEntry();
            }

            widget.setLocation(tempFile.toURI());
            widget.setId(tmpWidgetId);
            widget.setLastModified(tempFile.lastModified());
            widget.setCategory(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET);
            widget.setVersion(new Version(
                    manifest.getMainAttributes().getValue(FelixOSGiContainer.BUNDLE_VERSION_HEADER)));
        } else {
            throw new MMPException("Invalid module archive, missing "
                    + FelixOSGiContainer.BUNDLE_SYMBOLICNAME_HEADER + " header");
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy widget", ioe);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException ioe) {
                //NOP
            }
        }
        if (zout != null)
            try {
                zout.close();
            } catch (IOException ioe) {
                //NOP
            }
    }

    MMPOSGiContainer moduleContainer = (MMPOSGiContainer) ModuleContainerFactory.getInstance()
            .getModuleContainer();
    moduleContainer.deployModule(new File(widget.getLocation()));

    return widget;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Writes a .SF file with a digest to the manifest.
 *//*  ww  w.  j  ava  2 s  .  c o m*/
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            SdkConstants.UTF_8);

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download./* w  w w .j  a va 2 s . c  o m*/
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

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);
    zos.closeEntry();//from w  w  w  . j a  va  2 s . c o  m

    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.felix.deploymentadmin.itest.util.DPSigner.java

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

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