Example usage for java.util.jar Manifest getMainAttributes

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

Introduction

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

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

From source file:net.cliseau.composer.javatarget.PointcutParseException.java

/**
 * Update the manifest of a given JAR file to include CliSeAu's dependencies in the classpath list.
 *
 * This method modifies the "Class-Path" entry of the given JAR file's
 * manifest to include the paths of all runtime dependencies that are caused
 * by the instrumentation with the CliSeAu unit.
 *
 * @param targetJARFile The JAR file whose manifest to update.
 * @exception IOException Thrown when reading or writing the JAR file fails.
 * @todo Check whether this update is possible also with the JarFile API alone.
 *//*from   w  w  w . ja v a 2s  .co m*/
private void updateTargetManifest(final File targetJARFile) throws IOException, InvalidConfigurationException {
    // Step 1: Obtain the existing class path list from the target JAR file
    JarFile targetJAR = new JarFile(targetJARFile);
    Manifest targetManifest = targetJAR.getManifest();
    LinkedList<String> classPathEntries;
    if (targetManifest != null) {
        String targetClassPath = targetManifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
        if (targetClassPath == null) {
            targetClassPath = "";
        }
        classPathEntries = new LinkedList<String>(
                Arrays.asList(targetClassPath.split(manifestClassPathSeparator)));
    } else {
        classPathEntries = new LinkedList<String>();
    }
    // close the object again (this shall ensure that the command in
    // Step 4 can safely work on the file again)
    targetJAR.close();

    // Step 2: Add all newly introduced runtime dependencies of CliSeAu
    classPathEntries.addAll(getInlinedDependencies());

    // Step 3: Create a new manifest file with *only* the updated class path directive
    File manifestUpdate = File.createTempFile("MANIFEST", ".MF");
    PrintWriter muWriter = new PrintWriter(manifestUpdate);
    muWriter.print("Class-path:");
    muWriter.print(StringUtils.join(classPathEntries, manifestClassPathSeparator));
    muWriter.println();
    muWriter.close();

    // Step 4: Run "jar" to update the JAR file with the new manifest; this
    // does not replace the JAR file's manifest with the new one, but
    // *update* *only* those entries in the JAR file's manifest which are
    // present in the new manifest. That is, only the class path settings are
    // updated and everything else remains intact.
    CommandRunner.exec(new String[] { aspectjConfig.getJarExecutable(), "umf", // update manifest
            manifestUpdate.getPath(), targetJARFile.getPath() });

    // Step 5: cleanup
    manifestUpdate.delete();
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;/*w w w .  j a v  a  2 s  . c  o  m*/
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }/*  w w w .  j a v a2s  .co m*/
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkUniversalLibrary() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestLib.jar");

    // prepare file with ldFlags
    String flags = "-lTestLibrary";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();//from  w w  w .j a  v  a  2  s .co m
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL library = cl.getResource("natives/universal/libTestLibrary.a");
    URL headersURL = cl.getResource("natives/Headers/TestFramework.h");

    File headers = new File(headersURL.getPath());
    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--library", library.getPath(), "--headers",
            headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path",
            outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";")));
    realLDFlags.add("-ObjC");
    assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";"))));

    String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_universal");
    assertEquals(manifestSimFramework, "./lib/libTestLibrary.a");

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals(manifestBundle, "./bundle/moe_logo.png;");

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/libTestLibrary.a"));

    jarFile.close();

}

From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java

/**
 * Creates the default manifest in case none if found on the disk. By
 * default, the imports are synthetised based on the test class bytecode.
 * //from   w  w w  .  ja v a2s . c  o  m
 * @return default manifest for the jar created on the fly
 */
protected Manifest createDefaultManifest() {
    Manifest manifest = new Manifest();
    Attributes attrs = manifest.getMainAttributes();

    // manifest versions
    attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    attrs.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");

    String description = getName() + "-" + getClass().getName();
    // name/description
    attrs.putValue(Constants.BUNDLE_NAME, "TestBundle-" + description);
    attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "TestBundle-" + description);
    attrs.putValue(Constants.BUNDLE_DESCRIPTION, "on-the-fly test bundle");

    // activator
    attrs.putValue(Constants.BUNDLE_ACTIVATOR, JUnitTestActivator.class.getName());

    // add Import-Package entry
    addImportPackage(manifest);

    if (logger.isDebugEnabled())
        logger.debug("Created manifest:" + manifest.getMainAttributes().entrySet());
    return manifest;
}

From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java

private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    InstallationResult result = null;//from  w ww. j  a  va2 s  .c  o m

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // try to hold even largish bundles in memory to potentially improve performance
        factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD);

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(req);
        if (items.size() != 1) {
            logAndWriteError(
                    "Found " + items.size() + " items to process, but only updating 1 bundle is supported",
                    resp);
            return;
        }

        FileItem item = items.get(0);

        JarInputStream jar = null;
        InputStream rawInput = null;
        try {
            jar = new JarInputStream(item.getInputStream());
            Manifest manifest = jar.getManifest();
            if (manifest == null) {
                logAndWriteError("Uploaded jar file does not contain a manifest", resp);
                return;
            }

            final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);

            if (symbolicName == null) {
                logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp);
                return;
            }

            final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);

            // the JarInputStream is used only for validation, we need a fresh input stream for updating
            rawInput = item.getInputStream();

            Bundle found = getBundle(symbolicName);
            try {
                installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar");

                result = new InstallationResult(true, null);
                resp.setStatus(200);
                result.render(resp.getWriter());
                return;
            } catch (BundleException e) {
                logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp);
                return;
            }
        } finally {
            IOUtils.closeQuietly(jar);
            IOUtils.closeQuietly(rawInput);
        }

    } catch (FileUploadException e) {
        logAndWriteError("Failed parsing uploaded bundle", e, resp);
        return;
    }
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkFramework() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestFramework.jar");

    // prepare file with ldFlags
    String flags = "-framework TestFramework";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();/*from w  ww .j  av  a 2s  .  co  m*/
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL simFramework = cl.getResource("natives/device/TestFramework.framework");
    URL devFramework = cl.getResource("natives/simulator/TestFramework.framework");

    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--framework",
            String.format("%s:%s", simFramework.getPath(), devFramework.getPath()), "--package-name", "org",
            "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle",
            bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyFrameworkLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    assertEquals(flags + ";", manifestLDFlags);

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals(manifestBundle, "./bundle/moe_logo.png;");

    String manifestFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator");
    assertEquals(manifestFramework, "./lib/iphonesimulator/TestFramework.framework");

    String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device");
    assertEquals(manifestDevFramework, "./lib/iphoneos/TestFramework.framework");

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/iphonesimulator/TestFramework.framework"));
    assertNotNull(jarFile.getEntry("lib/iphoneos/TestFramework.framework"));

    jarFile.close();

}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkLibrary() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestLib.jar");

    // prepare file with ldFlags
    String flags = "-lTestLibrary";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();//w  ww  .  j a va2  s.  c o m
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL library = cl.getResource("natives/simulator/libTestLibrary.a");
    URL deviceLibrary = cl.getResource("natives/device/libTestLibrary.a");
    URL headersURL = cl.getResource("natives/Headers/TestFramework.h");

    File headers = new File(headersURL.getPath());
    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--library",
            String.format("%s:%s", library.getPath(), deviceLibrary.getPath()), "--headers",
            headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path",
            outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";")));
    realLDFlags.add("-ObjC");
    assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";"))));

    String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator");
    assertEquals("./lib/iphonesimulator/libTestLibrary.a", manifestSimFramework);

    String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device");
    assertEquals("./lib/iphoneos/libTestLibrary.a", manifestDevFramework);

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals("./bundle/moe_logo.png;", manifestBundle);

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/iphonesimulator/libTestLibrary.a"));
    assertNotNull(jarFile.getEntry("lib/iphoneos/libTestLibrary.a"));

    jarFile.close();

}

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

/**
 * Add branch ID to a widget Manifest before deploying it
 * @param widgetFile/* w ww  .ja v a 2 s.  com*/
 * @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:net.sourceforge.jweb.maven.mojo.OneExecutablejarMojo.java

private Manifest getManifest() throws IOException {
    // Copy the template's boot-manifest.mf file
    ZipInputStream zipIS = openOnejarTemplateArchive();
    Manifest manifest = new Manifest(getFileBytes(zipIS, "boot-manifest.mf"));
    IOUtils.closeQuietly(zipIS);/*from  ww w .  ja  va  2s  . c  o m*/

    // If the client has specified a mainClass argument, add the proper entry to the manifest
    if (mainClass != null) {
        manifest.getMainAttributes().putValue("One-Jar-Main-Class", mainClass);
    }

    // If the client has specified an implementationVersion argument, add it also
    // (It's required and defaulted, so this always executes...)
    //
    // TODO: The format of this manifest entry is not "hard and fast".  Some specs call for "implementationVersion",
    // some for "implemenation-version", and others use various capitalizations of these two.  It's likely that a
    // better solution then this "brute-force" bit here is to allow clients to configure these entries from the
    // Maven POM.
    if (implementationVersion != null) {
        manifest.getMainAttributes().putValue("ImplementationVersion", implementationVersion);
    }

    return manifest;
}