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:com.bluexml.side.build.tools.reader.PluginReader.java

public Plugin read(File project) throws Exception {
    logger.debug("Read plugin :" + project.getName());
    // chemin vers le MANIFEST.MF

    File filePluginPath = new File(
            project.getAbsoluteFile() + File.separator + "META-INF" + File.separator + "MANIFEST.MF");

    FileInputStream fileInputStream;
    fileInputStream = new FileInputStream(filePluginPath);
    Manifest m = new Manifest(fileInputStream);

    String id = "";
    String version = "";
    String name = "";
    List<String> requiredBundle = new ArrayList<String>();

    for (Entry<Object, Object> ent : m.getMainAttributes().entrySet()) {
        String key = ent.getKey().toString();
        logger.debug("key :" + key);
        Object value = ent.getValue();
        logger.debug("* value :" + value);
        String string = value.toString();
        if (key.equals("Bundle-Version")) {
            version = string;//www.ja  v a 2  s.com
        } else if (key.equals("Bundle-SymbolicName")) {
            if (string.indexOf(";") == -1) {
                id = string;
            } else {
                id = string.substring(0, string.indexOf(";"));
            }
        } else if (key.equals("Bundle-Name")) {
            name = string;
        } else if (key.equals("Require-Bundle")) {
            String[] split = string.split(",");
            CollectionUtils.addAll(requiredBundle, split);

        }
    }

    logger.debug("Plugin ID :" + id);
    if (name.equals("%pluginName")) {
        // must read plugin.properties
        logger.debug("plugin name must be read from properties file");
    } else {
        logger.debug("Plugin Name :" + name);
    }
    logger.debug("Plugin Version :" + version);
    logger.debug("Required Bundles :" + requiredBundle);

    fileInputStream.close();

    Plugin p = new Plugin();
    p.setId(id);
    p.setVersion(version);
    p.setName(name);

    if (registries.pluginsRegister.containsKey(p.getId())) {
        logger.debug("this plugin exist in registry so we stop reading now");
        // stop to prevent loops between PluginReader -> extPReader -> constraints -> plugin
        return registries.pluginsRegister.get(p.getId());
    }

    if (addExtensions) {

        // extension
        // search plugin.xml if any
        File filePluginXMLPath = new File(project, "plugin.xml");

        if (filePluginXMLPath.exists()) {
            logger.debug("extension found :" + filePluginXMLPath);
            BlxExtensionPointReader extR = new BlxExtensionPointReader(registries, props);
            List<LinkedWithModule> lext = extR.read(filePluginXMLPath, p.getId());
            p.setExtensions(lext);
            for (LinkedWithModule extension : lext) {
                Utils.add(registries.tree, p, extension);
            }
        } else {
            logger.debug("Plugin do not have extension :" + filePluginXMLPath);
        }
    }
    if (addRequiredBundle) {
        // add dependencies
        for (String reqIdString : requiredBundle) {
            String reqId = reqIdString;
            String reqVersion = null;
            int indexOfSep = reqIdString.indexOf(";");
            if (indexOfSep != -1) {
                reqId = reqIdString.substring(0, indexOfSep);
                reqVersion = reqIdString.substring(indexOfSep);
            }

            // get the Object
            Plugin reqP = null;
            boolean side = true;

            if (registries.pluginsRegister.containsKey(p.getId())) {
                logger.debug("this plugin exist in registry so we stop reading now");
                reqP = registries.pluginsRegister.get(p.getId());
            } else {
                // need to read from plugin definition if source are available
                logger.debug("requeried Bundle " + reqId + " is not in register, try to read from FS");
                File featureFolder = registries.getProjectFolder(reqId, id);
                if (featureFolder != null) {
                    reqP = read(featureFolder);
                } else {
                    // not found in repository, not SIDE
                    side = false;
                    reqP = new Plugin();
                    reqP.setId(reqId);
                    if (reqVersion != null) {
                        reqP.setVersion(reqVersion);
                    }
                }
            }

            if (side || addAll) {
                registries.pluginsRegister.put(reqId, reqP);
                Utils.add(registries.tree, p, reqP);
                p.getDependecies().add(reqP);
            }
        }
    }
    return p;
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {/* w w  w .  j a  va  2s.  c  o m*/
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:org.apache.flink.client.web.JobsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter(ACTION_PARAM_NAME);

    if (action.equals(ACTION_LIST_VALUE)) {
        GregorianCalendar cal = new GregorianCalendar();

        File[] files = destinationDir.listFiles();
        Arrays.<File>sort(files, FILE_SORTER);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(CONTENT_TYPE_PLAIN);

        PrintWriter writer = resp.getWriter();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].getName().endsWith(".jar")) {
                continue;
            }//w w  w.  j a  v a2  s  .c om

            JarFile jar = new JarFile(files[i]);
            Manifest manifest = jar.getManifest();
            String assemblerClass = null;
            String descriptions = "";

            if (manifest != null) {
                assemblerClass = manifest.getMainAttributes()
                        .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_ASSEMBLER_CLASS);
                if (assemblerClass == null) {
                    assemblerClass = manifest.getMainAttributes()
                            .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_MAIN_CLASS);
                }
            }
            if (assemblerClass == null) {
                assemblerClass = "";
            } else {
                String[] classes = assemblerClass.split(",");
                for (String c : classes) {
                    try {
                        String d = new PackagedProgram(files[i], c, new String[0]).getDescription();
                        if (d == null) {
                            d = "No description provided.";
                        }
                        descriptions += "#_#" + d;
                    } catch (ProgramInvocationException e) {
                        descriptions += "#_#No description provided.";
                        continue;
                    }
                }

                assemblerClass = '\t' + assemblerClass;
            }

            cal.setTimeInMillis(files[i].lastModified());
            writer.println(files[i].getName() + '\t' + (cal.get(GregorianCalendar.MONTH) + 1) + '/'
                    + cal.get(GregorianCalendar.DAY_OF_MONTH) + '/' + cal.get(GregorianCalendar.YEAR) + ' '
                    + cal.get(GregorianCalendar.HOUR_OF_DAY) + ':' + cal.get(GregorianCalendar.MINUTE) + ':'
                    + cal.get(GregorianCalendar.SECOND) + assemblerClass + descriptions);
        }
    } else if (action.equals(ACTION_DELETE_VALUE)) {
        String filename = req.getParameter(FILENAME_PARAM_NAME);

        if (filename == null || filename.length() == 0) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            File f = new File(destinationDir, filename);
            if (!f.exists() || f.isDirectory()) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
            f.delete();
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /*from  w  w w.ja  v a  2  s.c  om*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /*  w ww  .j a va  2s. co m*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version.");
        ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java

public INeo4jRuntime getRuntimeFromLocation(IPath path) {
    INeo4jRuntime runtime = null;/*  www . ja  v  a  2  s . c  om*/
    File manifestMF = path.append(META_INF).append(MANIFEST_MF).toFile();
    if (manifestMF.exists()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(manifestMF);
            Manifest manifest = new Manifest(stream);
            String id = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLIC_NAME);
            String version = manifest.getMainAttributes().getValue(BUNDLE_VERSION);
            runtime = new Neo4jRuntime(version, id, path);
        } catch (Exception e) {
            Logger.log(Logger.SEVERITY_ERROR, e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }
    return runtime;
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4JRuntimesManager.java

public void initializeRuntimeMetadata(AbstractNeo4jRuntimeInstaller installer, IPath path) {
    File dirFile = path.toFile();
    File manifestFile = path.append(META_INF).append(MANIFEST_MF).toFile();
    FileOutputStream outputStream = null;
    try {//from w  ww. ja  v  a 2 s.c o  m
        FileUtils.forceMkdir(manifestFile.getParentFile());
        outputStream = new FileOutputStream(manifestFile);
        Manifest manifest = new Manifest();
        Attributes atts = manifest.getMainAttributes();
        atts.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        atts.putValue(BUNDLE_MANIFEST_VERSION, "2");
        atts.putValue(BUNDLE_NAME, installer.getName());
        atts.putValue(BUNDLE_SYMBOLIC_NAME, installer.getId());
        atts.putValue(BUNDLE_VERSION, installer.getVersion());
        atts.putValue(BUNDLE_CLASS_PATH, buildJarFilesList(dirFile));
        atts.putValue(EXPORT_PACKAGE, buildPackagesList(dirFile));
        manifest.write(outputStream);
        load();
    } catch (Exception e) {
        Logger.log(Logger.SEVERITY_ERROR, e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private Manifest getManifest() {
    HashCodeBuilder builder = new HashCodeBuilder(11, 17);
    for (CodeGenerator gen : getAllCurrentGenerators()) {
        builder.append(gen.hashForManifest());
    }/*from  w  w w. j  a va  2  s.  com*/

    Manifest manifest = new Manifest();
    Attributes mainAttributes = manifest.getMainAttributes();
    mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    mainAttributes.put(NUCLOS_CODE_NUCLET, "default");
    mainAttributes.put(NUCLOS_CODE_HASH, String.valueOf(builder.toHashCode()));
    return manifest;
}

From source file:org.springframework.boot.loader.tools.Repackager.java

private boolean alreadyRepackaged() throws IOException {
    try (JarFile jarFile = new JarFile(this.source)) {
        Manifest manifest = jarFile.getManifest();
        return (manifest != null && manifest.getMainAttributes().getValue(BOOT_VERSION_ATTRIBUTE) != null);
    }/* w w w  .ja  va 2 s.  c  o m*/
}

From source file:org.wso2.carbon.automation.engine.frameworkutils.CodeCoverageUtils.java

private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException {
    if (!jarFilePath.endsWith(".jar")) {
        throw new IllegalArgumentException(
                "Jar file should have the extension .jar. " + jarFilePath + " is invalid");
    }/*from w w w  .  j  av  a  2 s. c o  m*/
    JarFile jarFile = new JarFile(jarFilePath);
    Manifest manifest = jarFile.getManifest();
    if (manifest == null) {
        throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file");
    }
    String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator;
    String jarFileName = jarFilePath;
    if (jarFilePath.lastIndexOf(fileSeparator) != -1) {
        jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1);
    }
    ArchiveManipulator archiveManipulator = null;
    String tempExtractedDir = null;
    try {
        archiveManipulator = new ArchiveManipulator();
        tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator
                + jarFileName.substring(0, jarFileName.lastIndexOf('.'));
        ArchiveExtractorUtil.extractFile(jarFilePath, tempExtractedDir);
    } catch (Exception e) {
        log.error("Could not extract the file", e);
    } finally {
        jarFile.close();
    }
    String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package");
    if (dynamicImports != null) {
        manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*");
    } else {
        manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*");
    }
    File newManifest = new File(
            tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF");
    FileOutputStream manifestOut = null;
    try {
        manifestOut = new FileOutputStream(newManifest);
        manifest.write(manifestOut);
    } catch (IOException e) {
        log.error("Could not write content to new MANIFEST.MF file", e);
    } finally {
        if (manifestOut != null) {
            manifestOut.close();
        }
    }

    if (tempExtractedDir != null)
        archiveManipulator.archiveDir(jarFilePath, tempExtractedDir);

    FileUtils.forceDelete(newManifest);
}