return the main attributes from the jar manifest
968168
private Attributes getMainAttributes() {
        if (null == mainAttributes) {
            mainAttributes = getJarMainAttributes(pluginJar);
            String pluginName = mainAttributes.getValue(RUNDECK_PLUGIN_NAME);
            if(pluginName == null) {
                //Fallback to something that will rarely change
                //This is not ideal, but old plugins do not always have a name
                //set in the attributes
                pluginName = mainAttributes.getValue(RUNDECK_PLUGIN_CLASSNAMES);
            }
            pluginId = PluginUtils.generateShaIdFromName(pluginName);
        }
        return mainAttributes;
    }
1181568
def manifest(fix, include_extras):
    """"""
    all_guids = {}

    root = get_root()
    root_name = basepath(get_root())

    ok_checks = 0
    failed_checks = 0
    fixed_checks = 0
    echo_info("Validating all manifest.json files...")
    for check_name in sorted(os.listdir(root)):
        manifest_file = os.path.join(root, check_name, 'manifest.json')

        if file_exists(manifest_file):
            display_queue = []
            file_failures = 0
            file_fixed = False

            try:
                decoded = json.loads(read_file(manifest_file).strip(), object_pairs_hook=OrderedDict)
            except JSONDecodeError as e:
                failed_checks += 1
                echo_info("{}/manifest.json... ".format(check_name), nl=False)
                echo_failure("FAILED")
                echo_failure('  invalid json: {}'.format(e))
                continue

            # attributes are valid
            attrs = set(decoded)
            for attr in sorted(attrs - ALL_ATTRIBUTES):
                file_failures += 1
                display_queue.append((echo_failure, '  Attribute `{}` is invalid'.format(attr)))
            for attr in sorted(REQUIRED_ATTRIBUTES - attrs):
                file_failures += 1
                display_queue.append((echo_failure, '  Attribute `{}` is required'.format(attr)))

            # guid
            guid = decoded.get('guid')
            if guid in all_guids:
                file_failures += 1
                output = '  duplicate `guid`: `{}` from `{}`'.format(guid, all_guids[guid])
                if fix:
                    new_guid = uuid.uuid4()
                    all_guids[new_guid] = check_name
                    decoded['guid'] = new_guid

                    display_queue.append((echo_warning, output))
                    display_queue.append((echo_success, '  new `guid`: {}'.format(new_guid)))

                    file_failures -= 1
                    file_fixed = True
                else:
                    display_queue.append((echo_failure, output))
            elif not guid or not isinstance(guid, string_types):
                file_failures += 1
                output = '  required non-null string: guid'
                if fix:
                    new_guid = uuid.uuid4()
                    all_guids[new_guid] = check_name
                    decoded['guid'] = new_guid

                    display_queue.append((echo_warning, output))
                    display_queue.append((echo_success, '  new `guid`: {}'.format(new_guid)))

                    file_failures -= 1
                    file_fixed = True
                else:
                    display_queue.append((echo_failure, output))
            else:
                all_guids[guid] = check_name

            # manifest_version
            correct_manifest_version = '1.0.0'
            manifest_version = decoded.get('manifest_version')
            version_parts = parse_version_parts(manifest_version)
            if len(version_parts) != 3:
                file_failures += 1

                if not manifest_version:
                    output = '  required non-null string: manifest_version'
                else:
                    output = '  invalid `manifest_version`: {}'.format(manifest_version)

                if fix:
                    version_parts = parse_version_parts(correct_manifest_version)
                    decoded['manifest_version'] = correct_manifest_version

                    display_queue.append((echo_warning, output))
                    display_queue.append(
                        (echo_success, '  new `manifest_version`: {}'.format(correct_manifest_version))
                    )

                    file_failures -= 1
                    file_fixed = True
                else:
                    display_queue.append((echo_failure, output))

            if len(version_parts) == 3:
                about_exists = os.path.isfile(
                    os.path.join(root, check_name, 'datadog_checks', check_name, '__about__.py')
                )
                if version_parts >= [1, 0, 0]:
                    if 'version' in decoded and about_exists:
                        file_failures += 1
                        output = '  outdated field: version'

                        if fix:
                            del decoded['version']

                            display_queue.append((echo_warning, output))
                            display_queue.append((echo_success, '  removed field: version'))

                            file_failures -= 1
                            file_fixed = True
                        else:
                            display_queue.append((echo_failure, output))

                elif about_exists:
                    file_failures += 1
                    output = '  outdated `manifest_version`: {}'.format(manifest_version)

                    if fix:
                        decoded['manifest_version'] = correct_manifest_version

                        display_queue.append((echo_warning, output))
                        display_queue.append(
                            (echo_success, '  new `manifest_version`: {}'.format(correct_manifest_version))
                        )

                        if 'version' in decoded:
                            del decoded['version']
                            display_queue.append((echo_success, '  removed field: version'))

                        file_failures -= 1
                        file_fixed = True
                    else:
                        display_queue.append((echo_failure, output))
                else:
                    version = decoded.get('version')
                    version_parts = parse_version_parts(version)
                    if len(version_parts) != 3:
                        file_failures += 1

                        if not version:
                            display_queue.append((echo_failure, '  required non-null string: version'))
                        else:
                            display_queue.append((echo_failure, '  invalid `version`: {}'.format(version)))

            # integration_id
            integration_id = decoded.get('integration_id')
            if not re.search(INTEGRATION_ID_REGEX, integration_id):
                file_failures += 1
                output = 'integration_id contains invalid characters'
                display_queue.append((echo_failure, output))

            # maintainer
            if root_name == 'integrations-core':
                correct_maintainer = 'help@datadoghq.com'
                maintainer = decoded.get('maintainer')
                if maintainer != correct_maintainer:
                    file_failures += 1
                    output = '  incorrect `maintainer`: {}'.format(maintainer)

                    if fix:
                        decoded['maintainer'] = correct_maintainer

                        display_queue.append((echo_warning, output))
                        display_queue.append((echo_success, '  new `maintainer`: {}'.format(correct_maintainer)))

                        file_failures -= 1
                        file_fixed = True
                    else:
                        display_queue.append((echo_failure, output))

            # name
            correct_name = check_name
            name = decoded.get('name')
            if not isinstance(name, string_types) or name.lower() != correct_name.lower():
                file_failures += 1
                output = '  incorrect `name`: {}'.format(name)

                if fix:
                    decoded['name'] = correct_name

                    display_queue.append((echo_warning, output))
                    display_queue.append((echo_success, '  new `name`: {}'.format(correct_name)))

                    file_failures -= 1
                    file_fixed = True
                else:
                    display_queue.append((echo_failure, output))

            # short_description
            short_description = decoded.get('short_description')
            if not short_description or not isinstance(short_description, string_types):
                file_failures += 1
                display_queue.append((echo_failure, '  required non-null string: short_description'))
            if len(short_description) > 80:
                file_failures += 1
                display_queue.append((echo_failure, '  should contain 80 characters maximum: short_description'))

            # support
            correct_support = 'contrib' if root_name == 'integrations-extras' else 'core'
            support = decoded.get('support')
            if support != correct_support:
                file_failures += 1
                output = '  incorrect `support`: {}'.format(support)

                if fix:
                    decoded['support'] = correct_support

                    display_queue.append((echo_warning, output))
                    display_queue.append((echo_success, '  new `support`: {}'.format(correct_support)))

                    file_failures -= 1
                    file_fixed = True
                else:
                    display_queue.append((echo_failure, output))

            if include_extras:
                # supported_os
                supported_os = decoded.get('supported_os')
                if not supported_os or not isinstance(supported_os, list):
                    file_failures += 1
                    display_queue.append((echo_failure, '  required non-null sequence: supported_os'))
                else:
                    known_systems = {'linux', 'mac_os', 'windows'}
                    unknown_systems = sorted(set(supported_os) - known_systems)
                    if unknown_systems:
                        file_failures += 1
                        display_queue.append(
                            (echo_failure, '  unknown `supported_os`: {}'.format(', '.join(unknown_systems)))
                        )

                # public_title
                public_title = decoded.get('public_title')
                if not public_title or not isinstance(public_title, string_types):
                    file_failures += 1
                    display_queue.append((echo_failure, '  required non-null string: public_title'))
                else:
                    title_start = 'Datadog-'
                    title_end = ' Integration'
                    section_char_set = set(public_title[len(title_start) : -len(title_end)].lower())
                    check_name_char_set = set(check_name.lower())
                    character_overlap = check_name_char_set & section_char_set

                    correct_start = public_title.startswith(title_start)
                    correct_end = public_title.endswith(title_end)
                    overlap_enough = len(character_overlap) > int(len(check_name_char_set) * 0.5)

                    if not (correct_start and correct_end and overlap_enough):
                        file_failures += 1
                        display_queue.append((echo_failure, '  invalid `public_title`: {}'.format(public_title)))

                # categories
                categories = decoded.get('categories')
                if not categories or not isinstance(categories, list):
                    file_failures += 1
                    display_queue.append((echo_failure, '  required non-null sequence: categories'))

                # type
                correct_integration_types = ['check', 'crawler']
                integration_type = decoded.get('type')
                if not integration_type or not isinstance(integration_type, string_types):
                    file_failures += 1
                    output = '  required non-null string: type'
                    display_queue.append((echo_failure, output))
                elif integration_type not in correct_integration_types:
                    file_failures += 1
                    output = '  invalid `type`: {}'.format(integration_type)
                    display_queue.append((echo_failure, output))

                # is_public
                correct_is_public = True
                is_public = decoded.get('is_public')
                if not isinstance(is_public, bool):
                    file_failures += 1
                    output = '  required boolean: is_public'

                    if fix:
                        decoded['is_public'] = correct_is_public

                        display_queue.append((echo_warning, output))
                        display_queue.append((echo_success, '  new `is_public`: {}'.format(correct_is_public)))

                        file_failures -= 1
                        file_fixed = True
                    else:
                        display_queue.append((echo_failure, output))

            if file_failures > 0:
                failed_checks += 1
                # Display detailed info if file invalid
                echo_info("{}/manifest.json... ".format(check_name), nl=False)
                echo_failure("FAILED")
                for display_func, message in display_queue:
                    display_func(message)
            elif not file_fixed:
                ok_checks += 1

            if fix and file_fixed:
                new_manifest = '{}\n'.format(json.dumps(decoded, indent=2, separators=(',', ': ')))
                write_file(manifest_file, new_manifest)
                # Display detailed info if file has been completely fixed
                if file_failures == 0:
                    fixed_checks += 1
                    echo_info("{}/manifest.json... ".format(check_name), nl=False)
                    echo_success("FIXED")
                    for display_func, message in display_queue:
                        display_func(message)

    if ok_checks:
        echo_success("{} valid files".format(ok_checks))
    if fixed_checks:
        echo_info("{} fixed files".format(fixed_checks))
    if failed_checks:
        echo_failure("{} invalid files".format(failed_checks))
        abort()
51213
def get_maven_id(jar_path):
        
        props = {}
        try:
            with zipfile.ZipFile(jar_path) as f:
                r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
                result = [x for x in f.namelist() if r.match(x)]
                if len(result) != 1:
                    return None
                with f.open(result[0]) as props_f:
                    for line in props_f.readlines():
                        line = line.strip()
                        if not line.startswith(b"#"):
                            try:
                                (key, value) = line.split(b"=")
                                key = key.decode('utf8').strip()
                                value = value.decode('utf8').strip()
                                props[key] = value
                            except ValueError:
                                return None
        except IOError:
            pass
        return props
931765
def GetAttributeNs(self, localName, namespaceURI):
        
        ret = libxml2mod.xmlTextReaderGetAttributeNs(self._o, localName, namespaceURI)
        return ret
1365114
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs attribute selection from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m")
    parser.add_argument("-i", metavar="input", dest="input", required=True, help="input file")
    parser.add_argument("-c", metavar="class index", dest="classindex", help="1-based class attribute index")
    parser.add_argument("-s", metavar="search", dest="search", help="search method, classname and options")
    parser.add_argument("-x", metavar="num folds", dest="numfolds", help="number of folds")
    parser.add_argument("-n", metavar="seed", dest="seed", help="the seed value for randomization")
    parser.add_argument("evaluator", help="evaluator classname, e.g., weka.attributeSelection.CfsSubsetEval")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="additional evaluator options")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)
    params = []
    if parsed.input is not None:
        params.extend(["-i", parsed.input])
    if parsed.classindex is not None:
        params.extend(["-c", parsed.classindex])
    if parsed.search is not None:
        params.extend(["-s", parsed.search])
    if parsed.numfolds is not None:
        params.extend(["-x", parsed.numfolds])
    if parsed.seed is not None:
        params.extend(["-n", parsed.seed])

    jvm.start(jars, max_heap_size=parsed.heap, packages=True)

    logger.debug("Commandline: " + join_options(sys.argv[1:]))

    try:
        evaluation = ASEvaluation(classname=parsed.evaluator)
        if len(parsed.option) > 0:
            evaluation.options = parsed.option
        print(AttributeSelection.attribute_selection(evaluation, params))
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
931602
private void scanJarManifestForClassPathEntries(LinkedList<WorkListItem> workList, ICodeBase codeBase) throws IOException {
        // See if this codebase has a jar manifest
        ICodeBaseEntry manifestEntry = codeBase.lookupResource("META-INF/MANIFEST.MF");
        if (manifestEntry == null) {
            // Do nothing - no Jar manifest found
            return;
        }

        // Try to read the manifest
        InputStream in = null;
        try {
            in = manifestEntry.openResource();
            Manifest manifest = new Manifest(in);

            Attributes mainAttrs = manifest.getMainAttributes();
            String classPath = mainAttrs.getValue("Class-Path");
            if (classPath != null) {
                String[] pathList = classPath.split("\\s+");

                for (String path : pathList) {
                    // Create a codebase locator for the classpath entry
                    // relative to the codebase in which we discovered the Jar
                    // manifest
                    ICodeBaseLocator relativeCodeBaseLocator = codeBase.getCodeBaseLocator().createRelativeCodeBaseLocator(path);

                    // Codebases found in Class-Path entries are always
                    // added to the aux classpath, not the application.
                    addToWorkList(workList, new WorkListItem(relativeCodeBaseLocator, false, ICodeBase.Discovered.IN_JAR_MANIFEST));
                }
            }
        } finally {
            if (in != null) {
                IO.close(in);
            }
        }
    }
1191476
def _manifest(self):
        """"""
        if self._manifest_cache is None:
            self._manifest_cache = self._storage_broker.get_manifest()

        return self._manifest_cache
1324597
protected String getManifestAttributeValue(Attributes.Name attributeName) {
        try {
            String value = attributes.getValue(attributeName);
            return value != null ? value : "undefined";
        } catch (NullPointerException e) {
            return "undefined";
        } catch (IllegalArgumentException e) {
            logger.error("Invalid attribute name when reading jar manifest for reading version information: " + e.getMessage());
            return "undefined";
        }
    }
773530
protected String getExecutableJar() throws IOException {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN);
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, getClasspath());

        Path jar = createTempDirectory("exec").resolve("generate.jar");
        try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {
            output.putNextEntry(new JarEntry("allure.properties"));
            Path allureConfig = PROPERTIES.getAllureConfig();
            if (Files.exists(allureConfig)) {
                byte[] bytes = Files.readAllBytes(allureConfig);
                output.write(bytes);
            }
            output.closeEntry();
        }

        return jar.toAbsolutePath().toString();
    }
710313
def get_public_attributes(cls, as_list=True):
    
    attrs = (a for a in dir(cls) if not a.startswith('_'))
    if as_list:
        return list(attrs)
    return attrs
254954
def get_main_section(self, linesep=None):
        

        linesep = linesep or self.linesep or os.linesep

        stream = BytesIO()
        ManifestSection.store(self, stream, linesep)
        return stream.getvalue()
471214
public Attributes getManifestAttributesFromURL(URL url) throws IOException {
        Manifest manifest = new Manifest(url.openStream());
        return manifest.getMainAttributes();
    }
440191
public Manifest getManifest()
    throws IOException
  {
    Manifest manifest;

    JarFile jarFile = getJarFile();

    try {
      if (jarFile == null)
        manifest = null;
      else
        manifest = jarFile.getManifest();
    } finally {
      closeJarFile(jarFile);
    }

    return manifest;
  }
591531
public Map<Object, Object> getManifestAttributes() {
		Map<Object, Object> manifestAttributes = null;
		
		manifestAttributes = getExplodedWarManifestAttributes();
		if (manifestAttributes == null) {
		    manifestAttributes = getPackagedWarManifestAttributes();
		}
		if (manifestAttributes == null) {
		    manifestAttributes = getClassPathManifestAttributes();
		}
		
		if (manifestAttributes == null) {
		    manifestAttributes = new HashMap<>();
		}
		return manifestAttributes;
	}
467318
public static String fromClassPath() {
        Set<String> versions = new HashSet<>();
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Enumeration<URL> manifests = classLoader.getResources("META-INF/MANIFEST.MF");

            while (manifests.hasMoreElements()) {
                URL manifestURL = manifests.nextElement();
                try (InputStream is = manifestURL.openStream()) {
                    Manifest manifest = new Manifest();
                    manifest.read(is);

                    Attributes buildInfo = manifest.getAttributes("Build-Info");
                    if (buildInfo != null) {
                        if (buildInfo.getValue("Selenium-Version") != null) {
                            versions.add(buildInfo.getValue("Selenium-Version"));
                        } else {
                            // might be in build-info part
                            if (manifest.getEntries() != null) {
                                if (manifest.getEntries().containsKey("Build-Info")) {
                                    final Attributes attributes = manifest.getEntries().get("Build-Info");

                                    if (attributes.getValue("Selenium-Version") != null) {
                                        versions.add(attributes.getValue("Selenium-Version"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.log(Level.WARNING,
                "Exception {0} occurred while resolving selenium version and latest image is going to be used.",
                e.getMessage());
            return SELENIUM_VERSION;
        }

        if (versions.isEmpty()) {
            logger.log(Level.INFO, "No version of Selenium found in classpath. Using latest image.");
            return SELENIUM_VERSION;
        }

        String foundVersion = versions.iterator().next();
        if (versions.size() > 1) {
            logger.log(Level.WARNING, "Multiple versions of Selenium found in classpath. Using the first one found {0}.",
                foundVersion);
        }

        return foundVersion;
    }
348742
def getAttributeNames(self):
        '''
        '''
        return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
1173250
private MBeanAttributeInfo[] getAttributeInfo() {
        final List<MBeanAttributeInfo> infoList = new ArrayList<>();

        if (type != null) {
            final List<String> attributes = new ArrayList<>();

            if (type.isInterface()) {
                ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
                    @Override
                    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                        String attributeName;

                        if (method.getName().startsWith("get")) {
                            attributeName = method.getName().substring(3);
                        } else if (method.getName().startsWith("is")) {
                            attributeName = method.getName().substring(2);
                        } else {
                            attributeName = method.getName();
                        }

                        if (!attributes.contains(attributeName)) {
                            infoList.add(new MBeanAttributeInfo(attributeName, method.getReturnType().getName(), ATTRIBUTE_DESCRIPTION, true, true, method.getName().startsWith("is")));
                            attributes.add(attributeName);
                        }
                    }
                }, new ReflectionUtils.MethodFilter() {
                    @Override
                    public boolean matches(Method method) {
                        return method.getDeclaringClass().equals(type) && (method.getName().startsWith("get") || method.getName().startsWith("is"));
                    }
                });
            } else {
                ReflectionUtils.doWithFields(type, new ReflectionUtils.FieldCallback() {
                    @Override
                    public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                        infoList.add(new MBeanAttributeInfo(field.getName(), field.getType().getName(), ATTRIBUTE_DESCRIPTION, true, true, field.getType().equals(Boolean.class)));
                    }
                }, new ReflectionUtils.FieldFilter() {
                    @Override
                    public boolean matches(Field field) {
                        return !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers());
                    }
                });
            }
        } else {
            int i = 1;
            for (ManagedBeanInvocation.Attribute attribute : attributes) {
                infoList.add(new MBeanAttributeInfo(attribute.getName(), attribute.getType(), ATTRIBUTE_DESCRIPTION, true, true, attribute.getType().equals(Boolean.class.getName())));
            }
        }

        return infoList.toArray(new MBeanAttributeInfo[infoList.size()]);
    }