Example usage for java.util.jar Attributes getValue

List of usage examples for java.util.jar Attributes getValue

Introduction

In this page you can find the example usage for java.util.jar Attributes getValue.

Prototype

public String getValue(Name name) 

Source Link

Document

Returns the value of the specified Attributes.Name, or null if the attribute was not found.

Usage

From source file:com.commercehub.dropwizard.BuildInfoServlet.java

@Override
public void init(ServletConfig config) {
    objectWriter = new ObjectMapper().writer();

    cacheControl = new CacheControl();
    cacheControl.setMustRevalidate(true);
    cacheControl.setNoCache(true);//from ww w  . j a v  a 2 s .  c o m
    cacheControl.setNoStore(true);

    // cache build information
    manifestAttributes = new Properties();
    ImmutableSet<String> attributeBlacklist = getAttributeBlacklist(config);
    try {
        Enumeration<URL> resources = getClass().getClassLoader().getResources(JarFile.MANIFEST_NAME);
        if (resources != null) {
            while (resources.hasMoreElements()) {
                Manifest manifest = new Manifest(resources.nextElement().openStream());
                Attributes attributes = manifest.getMainAttributes();
                for (Object key : attributes.keySet()) {
                    Attributes.Name attrName = (Attributes.Name) key;
                    if (!attributeBlacklist.contains(attrName.toString())) {
                        manifestAttributes.setProperty(attrName.toString(), attributes.getValue(attrName));
                    }
                }
            }
        }
    } catch (IOException e) {
        log.warn("Unable to retrieve build info", e);
    }
}

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

/**
 * Verifies the class file signatures of the specified map pack
 * //from  w  ww.  java 2 s  .c  o  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 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
 * //from w ww.  j  a  va  2 s .  c o 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:org.kepler.kar.karxml.KarXmlGenerator.java

/**
 * Read in the main attributes of the KAR and append them to the xml.
 * /*from w ww. ja  v a 2 s  .c o m*/
 * @throws IOException
 */
private void appendXmlForMainAttributes() throws IOException {

    karxml.append(tab + "<mainAttributes>" + nl);

    // gets the manifest
    Manifest mf = _karFile.getManifest();

    // gets the main attributes in the manifest
    Attributes atts = mf.getMainAttributes();
    if (atts != null) {
        String lsid = atts.getValue(KARFile.LSID);
        if (lsid != null) {
            karxml.append(tab + tab + "<" + KARFile.LSID + ">" + nl);
            karxml.append(tab + tab + tab + lsid + nl);
            karxml.append(tab + tab + "</" + KARFile.LSID + ">" + nl);
        }
        String moduleDependencies = atts.getValue(KARFile.MOD_DEPEND);
        if (moduleDependencies != null) {
            karxml.append(tab + tab + "<" + KARFile.MOD_DEPEND + ">" + nl);
            karxml.append(tab + tab + tab + moduleDependencies + nl);
            karxml.append(tab + tab + "</" + KARFile.MOD_DEPEND + ">" + nl);
        }
        String karVersion = atts.getValue(KARFile.KAR_VERSION);
        if (karVersion != null) {
            karxml.append(tab + tab + "<" + KARFile.KAR_VERSION + ">" + nl);
            karxml.append(tab + tab + tab + karVersion + nl);
            karxml.append(tab + tab + "</" + KARFile.KAR_VERSION + ">" + nl);
        }
        String manifestVersion = atts.getValue(_manifestVersion);
        if (manifestVersion != null) {
            karxml.append(tab + tab + "<" + _manifestVersion + ">" + nl);
            karxml.append(tab + tab + tab + manifestVersion + nl);
            karxml.append(tab + tab + "</" + _manifestVersion + ">" + nl);
        }
    }
    // Loop through the attributes
    /*for (Object att : atts.keySet()) {
            
       if (att instanceof Name) {
    Name attrName = (Name) att;
    String attrValue = atts.getValue(attrName);
            
    karxml.append(tab + tab + "<" + attrName + ">" + nl);
    karxml.append(tab + tab + tab + attrValue + nl);
    karxml.append(tab + tab + "</" + attrName + ">" + nl);
       } else {
    throw new IOException("Unrecognized Main Attribute");
       }
    }*/

    karxml.append(tab + "</mainAttributes>" + nl);
    //System.out.println("karxml is ==========\n "+karxml.toString());
}

From source file:com.datatorrent.stram.client.AppPackage.java

/**
 * Creates an App Package object./*from w  ww .j  ava  2 s  .com*/
 *
 * If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived
 * applications
 *
 * If contentFolder is not null, it will try to create the contentFolder, file will be retained on disk after App Package is closed
 * If contentFolder is null, temp folder will be created and will be cleaned on close()
 *
 * @param file
 * @param contentFolder  the folder that the app package will be extracted to
 * @param processAppDirectory
 * @throws java.io.IOException
 * @throws net.lingala.zip4j.exception.ZipException
 */
public AppPackage(File file, File contentFolder, boolean processAppDirectory) throws IOException, ZipException {
    super(file);

    if (contentFolder != null) {
        FileUtils.forceMkdir(contentFolder);
        cleanOnClose = false;
    } else {
        cleanOnClose = true;
        contentFolder = Files.createTempDirectory("dt-appPackage-").toFile();
    }
    directory = contentFolder;

    Manifest manifest = getManifest();
    if (manifest == null) {
        throw new IOException("Not a valid app package. MANIFEST.MF is not present.");
    }
    Attributes attr = manifest.getMainAttributes();
    appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
    appPackageVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_VERSION);
    appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
    dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION);
    appPackageDisplayName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DISPLAY_NAME);
    appPackageDescription = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DESCRIPTION);
    String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
    if (appPackageName == null || appPackageVersion == null || classPathString == null) {
        throw new IOException(
                "Not a valid app package.  App Package Name or Version or Class-Path is missing from MANIFEST.MF");
    }
    classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
    extractToDirectory(directory, file);
    if (processAppDirectory) {
        processAppDirectory(new File(directory, "app"));
    }
    File confDirectory = new File(directory, "conf");
    if (confDirectory.exists()) {
        processConfDirectory(confDirectory);
    }
    resourcesDirectory = new File(directory, "resources");

    File propertiesXml = new File(directory, "META-INF/properties.xml");
    if (propertiesXml.exists()) {
        processPropertiesXml(propertiesXml, null);
    }

    if (processAppDirectory) {
        for (AppInfo app : applications) {
            app.requiredProperties.addAll(requiredProperties);
            app.defaultProperties.putAll(defaultProperties);
            File appPropertiesXml = new File(directory, "META-INF/properties-" + app.name + ".xml");
            if (appPropertiesXml.exists()) {
                processPropertiesXml(appPropertiesXml, app);
            }
        }
    }
}

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

private void appendManifest(TinyBundle bundle) throws IOException {

    DefaultResourceLoader loader = new DefaultResourceLoader();
    Manifest manifest = new Manifest(loader.getResource(manifestLocation).getInputStream());
    Attributes attr = manifest.getMainAttributes();
    for (Object key : attr.keySet()) {
        String k = key.toString();
        String v = attr.getValue(k);

        // append optional import for org.ops4j.pax.exam
        if (k.equalsIgnoreCase(Constants.IMPORT_PACKAGE)) {
            if (StringUtils.hasText(v)) {
                v = v + ",";
            }/*from  w ww.  jav a  2  s.  c  om*/
        }
        v = v + "org.ops4j.pax.exam;resolution:=optional";
        bundle.set(k, v);
    }
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java

@Test
public void testBSNRenaming() throws Exception {
    // Provide the system with some artifacts that are known to be in the local .m2 repo
    // These are explicitly included in the test section of the pom.xml
    PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2",
            "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app",
            "org.apache.sling/org.apache.sling.commons.json/2.0.12");
    try {// w  ww .  j a v a 2 s  .  c o  m
        String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + ""
                + "[feature name=rename_test]\n"
                + "  org.apache.sling/org.apache.sling.commons.json/2.0.12 [bundle:rename-bsn=r-foo.bar.renamed.sling.commons.json]\n";

        Model model = ModelReader.read(new StringReader(modelTxt), null);
        ppm.execute(model);

        File orgJar = getMavenArtifactFile(getMavenRepoRoot(), "org.apache.sling",
                "org.apache.sling.commons.json", "2.0.12");
        File generatedJar = new File(ppm.getTmpDir() + "/r-foo.bar.renamed.sling.commons.json-2.0.12.jar");

        compareJarContents(orgJar, generatedJar);

        try (JarFile jfOrg = new JarFile(orgJar); JarFile jfNew = new JarFile(generatedJar)) {
            Manifest mfOrg = jfOrg.getManifest();
            Manifest mfNew = jfNew.getManifest();

            Attributes orgAttrs = mfOrg.getMainAttributes();
            Attributes newAttrs = mfNew.getMainAttributes();
            for (Object key : orgAttrs.keySet()) {
                String orgVal = orgAttrs.getValue(key.toString());
                String newVal = newAttrs.getValue(key.toString());

                if ("Bundle-SymbolicName".equals(key.toString())) {
                    assertEquals("Should have recorded the original Bundle-SymbolicName", orgVal,
                            newAttrs.getValue("X-Original-Bundle-SymbolicName"));

                    assertEquals("r-foo.bar.renamed.sling.commons.json", newVal);
                } else {
                    assertEquals("Different keys: " + key, orgVal, newVal);
                }
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory()));
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.dialogs.About.java

@SuppressWarnings("unchecked")
private void startup() {
    try {//from  ww  w  . ja va2s  .c o  m
        try {
            theFormControl = new FormControl(this, theSettingsPath);
        } catch (Exception ex) {
            LOG.error("Error loading form parameters", ex);
        }
        ClassLoader cLoader = Thread.currentThread().getContextClassLoader();
        Toolkit kit = Toolkit.getDefaultToolkit();
        Package p = this.getClass().getPackage();
        lblVersion.setText(p.getImplementationVersion());
        if (new File(theLogoFileName).exists()) {
            theLogo = kit.getImage(theLogoFileName);
        } else {
            java.net.URL imageURL = cLoader.getResource(theLogoFileName);
            if (imageURL != null) {
                theLogo = kit.getImage(imageURL);
            }
        }
        if (theLogo != null) {
            lblBuildNo.setForeground(Color.white);
            lblBuildNoLabel.setForeground(Color.white);
            //lblHeader.setForeground(Color.white);
            lblVersion.setForeground(Color.white);
            lblVersionLabel.setForeground(Color.white);
            paintImage();
        }
        //String manifestFileName = "/META-INF/MANIFEST.MF";
        Class cls = this.getClass();

        String className = cls.getSimpleName();
        String classFileName = className + ".class";
        String pathToThisClass = cls.getResource(classFileName).toString();
        int mark = pathToThisClass.indexOf("!");
        String pathToManifest = pathToThisClass.substring(0, mark + 1);
        if (!pathToManifest.equals("")) {
            pathToManifest += "/META-INF/MANIFEST.MF";
            LOG.debug("Path to manifest: " + pathToManifest);
            Manifest mf = new Manifest(new URL(pathToManifest).openStream());
            if (mf != null) {
                Attributes attr = mf.getMainAttributes();
                String attrVersion = "Implementation-Version";
                String attrBuild = "Implementation-Build";
                String version = attr.getValue(attrVersion);
                String build = attr.getValue(attrBuild);
                this.lblVersion.setText(version);
                this.lblBuildNo.setText(build);
            }
        }
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        LOG.debug("free memory: " + freeMemory / 1024);
        LOG.debug("allocated memory: " + allocatedMemory / 1024);
        LOG.debug("max memory: " + maxMemory / 1024);
        LOG.debug("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024);
    } catch (IOException ex) {
        ex.printStackTrace();
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:org.xwiki.extension.repository.internal.core.DefaultCoreExtensionScanner.java

@Override
public DefaultCoreExtension loadEnvironmentExtension(DefaultCoreExtensionRepository repository) {
    InputStream is = this.environment.getResourceAsStream("/META-INF/MANIFEST.MF");

    if (is != null) {
        // Probably running in an application server
        try {/*  w  w w . ja  v a 2s .  c om*/
            Manifest manifest = new Manifest(is);

            Attributes manifestAttributes = manifest.getMainAttributes();
            String extensionId = manifestAttributes.getValue(MavenUtils.MF_EXTENSION_ID);

            if (extensionId != null) {
                String[] mavenId = StringUtils.split(extensionId, ':');

                String descriptorPath = String.format("/META-INF/maven/%s/%s/pom.xml", mavenId[0], mavenId[1]);

                URL descriptorURL = this.environment.getResource(descriptorPath);

                if (descriptorURL != null) {
                    try {
                        DefaultCoreExtension coreExtension = parseMavenPom(descriptorURL, repository);

                        return coreExtension;
                    } catch (Exception e) {
                        this.logger.warn("Failed to parse extension descriptor [{}]", descriptorURL, e);
                    }
                } else {
                    this.logger.warn("Can't find resource file [{}] which contains distribution informations.",
                            descriptorPath);
                }
            }
        } catch (IOException e) {
            this.logger.error("Failed to parse environment META-INF/MANIFEST.MF file", e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    this.logger.debug("No declared environmennt extension");

    return null;
}