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: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  a  v  a2  s. c  o  m*/
    add(new File(folderName), target);
    target.close();
}

From source file:org.docx4j.jaxb.Context.java

public static void searchManifestsForJAXBImplementationInfo(ClassLoader loader) {
    Enumeration resEnum;//from   www .  j a  va 2 s  .co m
    try {
        resEnum = loader.getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            InputStream is = null;
            try {
                URL url = (URL) resEnum.nextElement();
                //                   System.out.println("\n\n" + url);
                is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);

                    Attributes mainAttribs = manifest.getMainAttributes();
                    String impTitle = mainAttribs.getValue("Implementation-Title");
                    if (impTitle != null && impTitle.contains("JAXB Reference Implementation")
                            || impTitle.contains("org.eclipse.persistence")) {

                        log.info("\n" + url);
                        for (Object key2 : mainAttribs.keySet()) {

                            log.info(key2 + " : " + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                        }
                    }

                    // In 2.1.3, it is in here
                    for (String key : manifest.getEntries().keySet()) {
                        //System.out.println(key);                       
                        if (key.equals("com.sun.xml.bind.v2.runtime")) {
                            log.info("Found JAXB reference implementation in " + url);
                            mainAttribs = manifest.getAttributes((String) key);

                            for (Object key2 : mainAttribs.keySet()) {
                                log.info(key2 + " : "
                                        + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                            }
                        }
                    }

                }
            } catch (Exception e) {
                // Silently ignore 
                //                  log.error(e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e1) {
        // Silently ignore 
        //           log.error(e1);
    }

}

From source file:jenkins.security.ClassFilterImpl.java

private static boolean isPluginManifest(Manifest mf) {
    Attributes attr = mf.getMainAttributes();
    return attr.getValue("Short-Name") != null
            && (attr.getValue("Plugin-Version") != null || attr.getValue("Jenkins-Version") != null)
            || "true".equals(attr.getValue("Jenkins-ClassFilter-Whitelisted"));
}

From source file:adalid.util.info.JavaInfo.java

public static void printManifestInfo(String path, String name, boolean details, Manifest manifest) {
    Object object;// ww  w .java 2 s.  co  m
    String string;
    out.println(path);
    //      out.println(StringUtils.leftPad(++fileCount + "", 4, '0') + ":" + name);
    out.println(name);
    Attributes attributes = manifest.getMainAttributes();
    Map<String, Object> sortedAttributes;
    if (details) {
        sortedAttributes = sort(attributes);
        for (String key : sortedAttributes.keySet()) {
            object = sortedAttributes.get(key);
            if (object != null) {
                out.println("\t" + key + ": " + object);
            }
        }
    } else {
        for (Attributes.Name attribute : ATTRIBUTE_NAMES) {
            string = attributes.getValue(attribute);
            if (StringUtils.isNotBlank(string)) {
                out.println("\t" + attribute + ": " + string);
            }
        }
    }
    out.println();
}

From source file:com.sinosoft.one.mvc.scanning.ResourceRef.java

public static ResourceRef toResourceRef(Resource folder) throws IOException {
    ResourceRef rr = new ResourceRef(folder, null, null);
    String[] modifiers = null;/*from  w  w  w.  jav  a2  s. c  o  m*/
    Resource mvcPropertiesResource = rr.getInnerResource("META-INF/mvc.properties");
    if (mvcPropertiesResource.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("found mvc.properties: " + mvcPropertiesResource.getURI());
        }
        InputStream in = mvcPropertiesResource.getInputStream();
        rr.properties.load(in);
        in.close();
        String attrValue = rr.properties.getProperty("mvc");
        if (attrValue == null) {
            attrValue = rr.properties.getProperty("Mvc");
        }
        if (attrValue != null) {
            modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by properties][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        }
    }
    //
    if (modifiers == null) {
        if (!"jar".equals(rr.getProtocol())) {
            modifiers = new String[] { "**" };
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by default][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        } else {
            JarFile jarFile = new JarFile(rr.getResource().getFile());
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                Attributes attributes = manifest.getMainAttributes();
                String attrValue = attributes.getValue("mvc");
                if (attrValue == null) {
                    attrValue = attributes.getValue("Mvc");
                }
                if (attrValue != null) {
                    modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
                    if (logger.isDebugEnabled()) {
                        logger.debug("modifiers[by manifest.mf][" + rr.getResource().getURI() + "]="
                                + Arrays.toString(modifiers));
                    }
                }
            }
        }
    }
    rr.setModifiers(modifiers);
    return rr;
}

From source file:com.gzj.tulip.load.ResourceRef.java

public static ResourceRef toResourceRef(Resource folder) throws IOException {
    ResourceRef rr = new ResourceRef(folder, null, null);
    String[] modifiers = null;//from  w  w w  .  j  a  va  2  s. co  m
    Resource rosePropertiesResource = rr.getInnerResource("META-INF/rose.properties");
    if (rosePropertiesResource.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("found rose.properties: " + rosePropertiesResource.getURI());
        }
        InputStream in = rosePropertiesResource.getInputStream();
        rr.properties.load(in);
        in.close();
        String attrValue = rr.properties.getProperty("rose");
        if (attrValue == null) {
            attrValue = rr.properties.getProperty("Rose");
        }
        if (attrValue != null) {
            modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by properties][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        }
    }
    //
    if (modifiers == null) {
        if (!"jar".equals(rr.getProtocol())) {
            modifiers = new String[] { "**" };
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by default][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        } else {
            JarFile jarFile = new JarFile(rr.getResource().getFile());
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                Attributes attributes = manifest.getMainAttributes();
                String attrValue = attributes.getValue("rose");
                if (attrValue == null) {
                    attrValue = attributes.getValue("Rose");
                }
                if (attrValue != null) {
                    modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
                    if (logger.isDebugEnabled()) {
                        logger.debug("modifiers[by manifest.mf][" + rr.getResource().getURI() + "]="
                                + Arrays.toString(modifiers));
                    }
                }
            }
        }
    }
    rr.setModifiers(modifiers);
    return rr;
}

From source file:org.lamport.tla.toolbox.jcloud.PayloadHelper.java

public static Payload appendModel2Jar(final Path modelPath, String mainClass, Properties properties,
        IProgressMonitor monitor) throws IOException {

    /*//from  w  w w  .  jav a2  s .c  o m
     * Get the standard tla2tools.jar from the classpath as a blueprint.
     * It's located in the org.lamport.tla.toolbox.jclouds bundle in the
     * files/ directory. It uses OSGi functionality to read files/tla2tools.jar
     * from the .jclouds bundle.
     * The copy of the blueprint will contain the spec & model and 
     * additional metadata (properties, amended manifest).
     */
    final Bundle bundle = FrameworkUtil.getBundle(PayloadHelper.class);
    final URL toolsURL = bundle.getEntry("files/tla2tools.jar");
    if (toolsURL == null) {
        throw new RuntimeException("No tlatools.jar and/or spec to deploy");
    }

    /* 
     * Copy the tla2tools.jar blueprint to a temporary location on
     * disk to append model files below.
     */
    final File tempFile = File.createTempFile("tla2tools", ".jar");
    tempFile.deleteOnExit();
    try (FileOutputStream out = new FileOutputStream(tempFile)) {
        IOUtils.copy(toolsURL.openStream(), out);
    }

    /*
     * Create a virtual filesystem in jar format.
     */
    final Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    final URI uri = URI.create("jar:" + tempFile.toURI());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        /*
         * Copy the spec and model into the jar's model/ folder.
         * Also copy any module override (.class file) into the jar.
         */
        try (DirectoryStream<Path> modelDirectoryStream = Files.newDirectoryStream(modelPath,
                "*.{cfg,tla,class}")) {
            for (final Path file : modelDirectoryStream) {
                final Path to = fs.getPath("/model/" + file.getFileName());
                Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING);
            }
        }

        /*
         * Add given class as Main-Class statement to jar's manifest. This
         * causes Java to launch this class when no other Main class is 
         * given on the command line. Thus, it shortens the command line
         * for us.
         */
        final Path manifestPath = fs.getPath("/META-INF/", "MANIFEST.MF");
        final Manifest manifest = new Manifest(Files.newInputStream(manifestPath));
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
        final PipedOutputStream ps = new PipedOutputStream();
        final PipedInputStream is = new PipedInputStream(ps);
        manifest.write(ps);
        ps.close();
        Files.copy(is, manifestPath, StandardCopyOption.REPLACE_EXISTING);

        /*
         * Add properties file to archive. The property file contains the
         * result email address... from where TLC eventually reads it.
         */

        // On Windows 7 and above the file has to be created in the system's
        // temp folder. Otherwise except file creation to fail with a
        // AccessDeniedException
        final File f = File.createTempFile("generated", "properties");
        OutputStream out = new FileOutputStream(f);
        // Append all entries in "properties" to the temp file f
        properties.store(out, "This is an optional header comment string");
        // Copy the temp file f into the jar with path /model/generated.properties.
        final Path to = fs.getPath("/model/generated.properties");
        Files.copy(f.toPath(), to, StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e1) {
        throw new RuntimeException("No model directory found to deploy", e1);
    }

    /*
     * Compress archive with pack200 to achieve a much higher compression rate. We
     * are going to send the file on the wire after all:
     * 
     * effort: take more time choosing codings for better compression segment: use
     * largest-possible archive segments (>10% better compression) mod time: smear
     * modification times to a single value deflate: ignore all JAR deflation hints
     * in original archive
     */
    final Packer packer = Pack200.newPacker();
    final Map<String, String> p = packer.properties();
    p.put(Packer.EFFORT, "9");
    p.put(Packer.SEGMENT_LIMIT, "-1");
    p.put(Packer.MODIFICATION_TIME, Packer.LATEST);
    p.put(Packer.DEFLATE_HINT, Packer.FALSE);

    // Do not reorder which changes package names. Pkg name changes e.g. break
    // SimpleFilenameToStream.
    p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE);

    // Throw an error if any of the above attributes is unrecognized.
    p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);

    final File packTempFile = File.createTempFile("tla2tools", ".pack.gz");
    try (final JarFile jarFile = new JarFile(tempFile);
            final GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(packTempFile));) {
        packer.pack(jarFile, fos);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to pack200 the tla2tools.jar file", ioe);
    }

    /*
     * Convert the customized tla2tools.jar into a jClouds payload object. This is
     * the format it will be transfered on the wire. This is handled by jClouds
     * though.
     */
    Payload jarPayLoad = null;
    try {
        final InputStream openStream = new FileInputStream(packTempFile);
        jarPayLoad = Payloads.newInputStreamPayload(openStream);
        // manually set length of content to prevent a NPE bug
        jarPayLoad.getContentMetadata().setContentLength(Long.valueOf(openStream.available()));
    } catch (final IOException e1) {
        throw new RuntimeException("No tlatools.jar to deploy", e1);
    } finally {
        monitor.worked(5);
    }

    return jarPayLoad;
}

From source file:com.conversantmedia.mapreduce.tool.RunJob.java

private static String readVersionFromManifest(String version) {
    // Try again to see if this class's MANIFEST was unjar'd by the hadoop command
    // - read it from the unjar'd file instead.
    InputStream in = null;/*  ww w . ja  va 2s .  com*/
    try {
        URL manifestUrl = findManifestForDriver();
        if (manifestUrl != null) {
            in = manifestUrl.openStream();
            Manifest manifest = new Manifest(in);
            version = manifest.getMainAttributes().getValue("Implementation-Version");
        }
    } catch (Exception e) {
        // No point in exiting the app because we fail to read version from manifest.
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(in);
    }
    return version;
}

From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java

/**
 * /* w  w w. j  a  va  2 s . co  m*/
 * @param clazz Class
 * @return String
 */
public static String readJarManifestForClass(Class<?> clazz) {
    StringBuilder sb = new StringBuilder();
    InputStream manifestInputStream = null;

    try {

        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        if (!classPath.startsWith("jar")) {
            // Class not from JAR
            return "Class " + className + " not from jar file.";
        }

        String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
        manifestInputStream = new URL(manifestPath).openStream();
        Manifest manifest = new Manifest(manifestInputStream);
        Attributes attr = manifest.getMainAttributes();
        // String value = attr.getValue("Manifest-Version");

        Set<Object> keys = attr.keySet();
        for (Object currKey : keys) {
            String currValue = attr.getValue(currKey.toString());
            if (currValue != null) {
                sb.append(currKey.toString()).append(" : ").append(currValue).append("\n");
            } else {
                sb.append(currKey.toString()).append(": Didn't have a value");
            }
        }
    } catch (Exception e) {
        logger.warning("Failed to read manifest for " + clazz.getSimpleName(), e);
    } finally {
        IOUtils.closeQuietly(manifestInputStream);
    }
    return sb.toString();
}

From source file:org.sonatype.nexus.plugins.p2.repository.metadata.AbstractP2MetadataSource.java

private static StorageFileItem compressMetadataItem(final Repository repository, final String path,
        final StorageFileItem metadataXml) throws IOException {
    final Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

    // this is a special one: once cached (hence consumed), temp file gets deleted
    final FileContentLocator fileContentLocator = new FileContentLocator("application/java-archive");

    try (OutputStream buffer = fileContentLocator.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(buffer);
            InputStream in = metadataXml.getInputStream()) {
        out.putNextEntry(new JarEntry(metadataXml.getName()));
        IOUtils.copy(in, out);/*from w ww . ja  v  a  2s. c  om*/
    }

    final DefaultStorageFileItem result = new DefaultStorageFileItem(repository, new ResourceStoreRequest(path),
            true /* isReadable */, false /* isWritable */, fileContentLocator);
    return result;
}