Example usage for java.util.jar Attributes get

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

Introduction

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

Prototype

public Object get(Object name) 

Source Link

Document

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

Usage

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

private static boolean extensionNameMatches(Manifest manifest, String regex) {
    if (StringUtils.isBlank(regex)) {
        return true;
    }//  w  ww . j a  v a  2s.c  o  m
    Attributes attributes = manifest.getMainAttributes();
    Object object = attributes.get(Attributes.Name.EXTENSION_NAME);
    if (object instanceof String) {
        String string = (String) object;
        return string.matches(regex);
    }
    return false;
}

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

private static Map<String, Object> sort(Attributes attributes) {
    Object object;/*  w  w  w  .j  a  va 2s. co  m*/
    Map<String, Object> map = new TreeMap<>();
    for (Object key : attributes.keySet()) {
        object = attributes.get(key);
        map.put(key.toString(), object);
    }
    return map;
}

From source file:ezbake.deployer.utilities.VersionHelper.java

private static String getVersionFromManifest(File artifact) throws IOException {
    String versionNumber = null;//from  w  ww  .  j a v  a 2s  .  c o m
    try (JarFile jar = new JarFile(artifact)) {
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        if (attributes != null) {
            for (Object o : attributes.keySet()) {
                Attributes.Name key = (Attributes.Name) o;
                String keyword = key.toString();
                if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")) {
                    versionNumber = (String) attributes.get(key);
                    break;
                }
            }
        }
    }
    return versionNumber;
}

From source file:com.vmware.vfabric.hyperic.plugin.vfws.BmxResult.java

public Properties parseToProperties() throws IOException {
    InputStream is = _response.getEntity().getContent();
    props = new Properties();

    Manifest manifest = new Manifest(is);
    Attributes attributes = manifest.getMainAttributes();
    if (null == attributes) {
        _log.error("Unable to parse results. No attributes found");
        return null;
    }/*  w  w  w.  ja va2s  . com*/

    for (Iterator<Object> it = attributes.keySet().iterator(); it.hasNext();) {
        Name key = (Name) it.next();
        if (key == null) {
            _log.debug("Skipping null key");
            continue;
        }
        Object value = attributes.get(key);
        if (value.getClass() != String.class) {
            _log.error("Attribute value not of class String");
            continue;
        }
        String keyName = key.toString();
        String val = (String) value;
        props.put(keyName, val);
    }
    return props;
}

From source file:com.vmware.vfabric.hyperic.plugin.vfws.VfwsCollector.java

private void parse(HttpResponse response) throws IOException {
    InputStream is = response.getEntity().getContent();

    if (is == null) {
        log.error("Unable to retrieve results. InputStream is null");
        return;/*from w  w  w. ja  v  a2s . c o m*/
    }

    Manifest manifest = new Manifest(is);
    Attributes attributes = manifest.getMainAttributes();
    if (null == attributes) {
        log.error("Unable to parse results. No attributes found");
        return;
    }

    Iterator it = attributes.keySet().iterator();
    while (it.hasNext()) {
        Name key = (Name) it.next();
        if (key == null) {
            log.debug("Skipping null key");
            continue;
        }
        Object value = attributes.get(key);
        if (value.getClass() != String.class) {
            log.error("Attribute value not of class String");
            continue;
        }
        String keyName = key.toString();
        String val = (String) value;
        // BusyWorkers and IdleWorkers have u in the values
        if (keyName.contains("Workers")) {
            setWorkers(keyName, val);
        } else if (keyName.contains("StartTime")) {
            setStartTime(keyName, val);
        } else {
            setValue(keyName, val);
        }
    }
}

From source file:com.slamd.admin.JobPack.java

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.//from w  ww.j  a  v  a2  s .c  o m
 *
 * @throws  SLAMDServerException  If a problem occurs while processing the job
 *                                pack JAR file.
 */
public void processJobPack() throws SLAMDServerException {
    byte[] fileData = null;
    File tempFile = null;
    String fileName = null;
    String separator = System.getProperty("file.separator");

    if (filePath == null) {
        // First, get the request and ensure it is multipart content.
        HttpServletRequest request = requestInfo.request;
        if (!FileUpload.isMultipartContent(request)) {
            throw new SLAMDServerException("Request does not contain multipart " + "content");
        }

        // Iterate through the request fields to get to the file data.
        Iterator iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) {
                fileData = fileItem.get();
                fileName = fileItem.getName();
            }
        }

        // Make sure that a file was actually uploaded.
        if (fileData == null) {
            throw new SLAMDServerException("No file data was found in the " + "request.");
        }

        // Write the JAR file data to a temp file, since that's the only way we
        // can parse it.
        if (separator == null) {
            separator = "/";
        }

        tempFile = new File(jobClassDirectory + separator + fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(fileData);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ioe) {
            try {
                tempFile.delete();
            } catch (Exception e) {
            }

            ioe.printStackTrace();
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
            throw new SLAMDServerException("I/O error writing temporary JAR " + "file:  " + ioe, ioe);
        }
    } else {
        tempFile = new File(filePath);
        if ((!tempFile.exists()) || (!tempFile.isFile())) {
            throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist");
        }

        try {
            fileName = tempFile.getName();
            int fileLength = (int) tempFile.length();
            fileData = new byte[fileLength];

            FileInputStream inputStream = new FileInputStream(tempFile);
            int bytesRead = 0;
            while (bytesRead < fileLength) {
                bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
            throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e);
        }
    }

    StringBuilder htmlBody = requestInfo.htmlBody;

    // Parse the jar file
    JarFile jarFile = null;
    Manifest manifest = null;
    Enumeration jarEntries = null;
    try {
        jarFile = new JarFile(tempFile, true);
        manifest = jarFile.getManifest();
        jarEntries = jarFile.entries();
    } catch (IOException ioe) {
        try {
            if (filePath == null) {
                tempFile.delete();
            }
        } catch (Exception e) {
        }

        ioe.printStackTrace();
        slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
        throw new SLAMDServerException("Unable to parse the JAR file:  " + ioe, ioe);
    }

    ArrayList<String> dirList = new ArrayList<String>();
    ArrayList<String> fileNameList = new ArrayList<String>();
    ArrayList<byte[]> fileDataList = new ArrayList<byte[]>();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        String entryName = jarEntry.getName();
        if (jarEntry.isDirectory()) {
            dirList.add(entryName);
        } else {
            try {
                int entrySize = (int) jarEntry.getSize();
                byte[] entryData = new byte[entrySize];
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                extractFileData(inputStream, entryData);
                fileNameList.add(entryName);
                fileDataList.add(entryData);
            } catch (IOException ioe) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe);
            } catch (SLAMDServerException sse) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                sse.printStackTrace();
                throw sse;
            }
        }
    }

    // If we have gotten here, then we have read all the data from the JAR file.
    // Delete the temporary file to prevent possible (although unlikely)
    // conflicts with data contained in the JAR.
    try {
        jarFile.close();
        if (filePath == null) {
            tempFile.delete();
        }
    } catch (Exception e) {
    }

    // Create the directory structure specified in the JAR file.
    if (!dirList.isEmpty()) {
        htmlBody.append("<B>Created the following directories</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < dirList.size(); i++) {
            File dirFile = new File(jobClassDirectory + separator + dirList.get(i));
            try {
                dirFile.mkdirs();
                htmlBody.append("  <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (Exception e) {
                htmlBody.append("</UL>" + Constants.EOL);
                e.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
                throw new SLAMDServerException(
                        "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Write all the files to disk.  If we have gotten this far, then there
    // should not be any failures, but if there are, then we will have to
    // leave things in a "dirty" state.
    if (!fileNameList.isEmpty()) {
        htmlBody.append("<B>Created the following files</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < fileNameList.size(); i++) {
            File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i));

            try {
                // Make sure the parent directory exists.
                dataFile.getParentFile().mkdirs();
            } catch (Exception e) {
            }

            try {
                FileOutputStream outputStream = new FileOutputStream(dataFile);
                outputStream.write(fileDataList.get(i));
                outputStream.flush();
                outputStream.close();
                htmlBody.append("  <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (IOException ioe) {
                htmlBody.append("</UL>" + Constants.EOL);
                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Finally, parse the manifest to get the names of the classes that should
    // be registered with the SLAMD server.
    Attributes manifestAttributes = manifest.getMainAttributes();
    Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR);
    String registerClassesStr = (String) manifestAttributes.get(key);
    if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) {
        htmlBody.append("<B>No job classes registered</B>" + Constants.EOL);
    } else {
        ArrayList<String> successList = new ArrayList<String>();
        ArrayList<String> failureList = new ArrayList<String>();

        StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n");
        while (tokenizer.hasMoreTokens()) {
            String className = tokenizer.nextToken();

            try {
                JobClass jobClass = slamdServer.loadJobClass(className);
                slamdServer.addJobClass(jobClass);
                successList.add(className);
            } catch (Exception e) {
                failureList.add(className + ":  " + e);
            }
        }

        if (!successList.isEmpty()) {
            htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < successList.size(); i++) {
                htmlBody.append("  <LI>" + successList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }

        if (!failureList.isEmpty()) {
            htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < failureList.size(); i++) {
                htmlBody.append("  <LI>" + failureList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }
    }
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

/**
 * Reads the signature file (if any) on the zip file.
 * <p>//from   w w w . j av  a  2s.  c o m
 * When this method terminates, we have the following guarantees:
 * <ul>
 *      <li>An internal signature manifest exists.</li>
 *      <li>All entries in the in-memory signature file exist in the zip file.</li>
 *      <li>All entries in the zip file (with the exception of the signature-related files,
 *      as specified by https://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html)
 *      exist in the in-memory signature file.</li>
 *      <li>All entries in the in-memory signature file have digests that match their
 *      contents in the zip.</li>
 *      <li>All entries in the in-memory signature manifest exist also in the manifest file
 *      and the digests are the same.</li>
 *      <li>The main attributes of the in-memory signature manifest are valid. The manifest's
 *      digest has not been verified and may not even exist.</li>
 *      <li>If the internal in-memory signature manifest differs in any way from the one
 *      written in the file, {@link #mDirty} will be set to {@code true}. Otherwise,
 *      {@link #mDirty} will be set to {@code false}.</li>
 * </ul>
 *
 * @throws IOException failed to read the signature file
 */
private void readSignatureFile() throws IOException {
    boolean needsNewSignature = false;

    StoredEntry signatureEntry = mManifestExtension.zFile().get(SIGNATURE_FILE);
    if (signatureEntry != null) {
        byte[] signatureData = signatureEntry.read();
        mSignatureFile.read(new ByteArrayInputStream(signatureData));

        Attributes mainAttrs = mSignatureFile.getMainAttributes();
        String versionName = mainAttrs.getValue(SIGNATURE_VERSION_NAME);
        String createdBy = mainAttrs.getValue(SIGNATURE_CREATED_BY_NAME);
        String apkSigned = mainAttrs.getValue(SIGNATURE_ANDROID_APK_SIGNED_NAME);

        if (!SIGNATURE_VERSION_VALUE.equals(versionName) || !SIGNATURE_CREATED_BY_VALUE.equals(createdBy)
                || mainAttrs.get(mDigestAlgorithm.manifestAttributeName) != null
                || !Objects.equal(mApkSignedHeaderValue, apkSigned)) {
            needsNewSignature = true;
        }
    } else {
        needsNewSignature = true;
    }

    if (needsNewSignature) {
        Attributes mainAttrs = mSignatureFile.getMainAttributes();

        mainAttrs.putValue(SIGNATURE_CREATED_BY_NAME, SIGNATURE_CREATED_BY_VALUE);
        mainAttrs.putValue(SIGNATURE_VERSION_NAME, SIGNATURE_VERSION_VALUE);
        if (mApkSignedHeaderValue != null) {
            mainAttrs.putValue(SIGNATURE_ANDROID_APK_SIGNED_NAME, mApkSignedHeaderValue);
        } else {
            mainAttrs.remove(SIGNATURE_ANDROID_APK_SIGNED_NAME);
        }

        mDirty = true;
    }

    /*
     * At this point we have a valid in-memory signature file with a valid header. mDirty
     * states whether this is the same as the file-based signature file.
     *
     * Now, check we have the same files in the zip as in the signature file and that all
     * digests match. While we do this, make sure the manifest is also up-do-date.
     *
     * We ignore all signature-related files that exist in the zip that are signature-related.
     * This are defined in the jar format specification.
     */
    Set<StoredEntry> allEntries = mManifestExtension.zFile().entries().stream()
            .filter(se -> !isIgnoredFile(se.getCentralDirectoryHeader().getName())).collect(Collectors.toSet());

    Set<String> sigEntriesToRemove = Sets.newHashSet(mSignatureFile.getEntries().keySet());
    Set<String> manEntriesToRemove = Sets.newHashSet(mManifestExtension.allEntries().keySet());
    for (StoredEntry se : allEntries) {
        /*
         * Update the entry's digest, if needed.
         */
        setDigestForEntry(se);

        /*
         * This entry exists in the file, so remove it from the list of entries to remove
         * from the manifest and signature file.
         */
        sigEntriesToRemove.remove(se.getCentralDirectoryHeader().getName());
        manEntriesToRemove.remove(se.getCentralDirectoryHeader().getName());
    }

    for (String toRemoveInSignature : sigEntriesToRemove) {
        mSignatureFile.getEntries().remove(toRemoveInSignature);
        mDirty = true;
    }

    for (String toRemoveInManifest : manEntriesToRemove) {
        mManifestExtension.removeEntry(toRemoveInManifest);
    }
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlProducesOsgiManifest() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleName, moduleVersion);

    Attributes attr = manifest.getMainAttributes();
    assertEquals("2", attr.get(OsgiUtil.OsgiManifest.Bundle_ManifestVersion));

    assertEquals(moduleName, attr.get(OsgiUtil.OsgiManifest.Bundle_SymbolicName));
    String bundleVersion = (String) attr.get(OsgiUtil.OsgiManifest.Bundle_Version);
    int qualifierIndex = bundleVersion.lastIndexOf('.');
    String bundleVersionWithoutQualifier = qualifierIndex > 0 ? bundleVersion.substring(0, qualifierIndex)
            : bundleVersion;/*w  w w.  j a  va  2  s. c  om*/
    assertEquals(moduleVersion, bundleVersionWithoutQualifier);
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestExportsSharedPackages() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon",
            "modules/osgi/a/b/package.ceylon", "modules/osgi/a/b/B.ceylon", "modules/osgi/a/c/package.ceylon",
            "modules/osgi/a/c/C.ceylon");

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleName, moduleVersion);
    assertNotNull(manifest);// w ww  .ja v  a 2 s .  c o  m

    Attributes attr = manifest.getMainAttributes();
    String attribute = (String) attr.get(OsgiUtil.OsgiManifest.Export_Package);

    String[] exportPackage = attribute.split(",");
    assertEquals(2, exportPackage.length);

    assertThat(Arrays.asList(exportPackage),
            CoreMatchers.hasItems(
                    "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a;version=" + moduleVersion,
                    "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a.c;version=" + moduleVersion));

    assertThat(Arrays.asList(exportPackage), CoreMatchers.not(CoreMatchers
            .hasItem("com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a.b;version=" + moduleVersion)));
}

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected Handler<?> loadInstance(SplitResult splitResult, final ClassLoader classLoader) throws IOException {
    if (splitResult == null) {
        throw new NullPointerException();
    }//from w w w  .  j  a va  2  s  . c  o m
    if (classLoader == null) {
        throw new NullPointerException();
    }
    final Attributes extensionAttributes = splitResult.manifest.getAttributes(MANIFEST_EXTENSION_NAME);
    if (extensionAttributes == null) {
        throw new IOException("There is no valid manifest in the provided jar.");
    }
    final Object dataFile = extensionAttributes.get(MANIFEST_DATE_FILE);
    if (!(dataFile instanceof String)) {
        throw new IOException("There is no valid " + MANIFEST_DATE_FILE + " attribute defined in manifest.");
    }
    final InputStream inputStream = classLoader.getResourceAsStream((String) dataFile);
    if (inputStream == null) {
        throw new FileNotFoundException("Could not find the resource " + dataFile + " which was defined by "
                + MANIFEST_DATE_FILE + " manifest entry of provided jar file.");
    }
    try {
        final ObjectInputStream ois = new ObjectInputStream(inputStream) {
            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
                return classLoader.loadClass(desc.getName());
            }
        };
        final Object result;
        try {
            result = ois.readObject();
        } catch (Exception e) {
            throw new IOException("Could not parse the resource " + dataFile + " which was defined by "
                    + MANIFEST_DATE_FILE + " manifest entry of provided jar file.", e);
        }
        if (!(result instanceof Handler)) {
            throw new IOException("The resource " + dataFile + " which was defined by " + MANIFEST_DATE_FILE
                    + " manifest entry of provided jar file does contain " + result
                    + " and not an object of type " + Handler.class.getName() + ".");
        }
        return (Handler) result;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}