Load and validate manifest against schema
    located at MANIFEST_SCHEMA_PATH.
487193
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None:
    
    schema_data = _load_schema_data()
    try:
        validate(manifest, schema_data)
    except jsonValidationError as e:
        raise ValidationError(
            f"Manifest invalid for schema version {schema_data['version']}. "
            f"Reason: {e.message}"
        )
60918
public function loadManifest()
    {
        if ($this->files->exists($this->manifestPath)) {
            return $this->files->getRequire($this->manifestPath);
        }

        return null;
    }
148588
public function load()
    {
        $path = $this->manifestPath.'/collections.json';

        if ($this->files->exists($path) and is_array($manifest = json_decode($this->files->get($path), true)))
        {
            foreach ($manifest as $key => $entry)
            {
                $entry = new Entry($entry['fingerprints'], $entry['development']);

                $this->entries->put($key, $entry);
            }
        }
    }
609267
def validation_schema(name):
    """"""
    schemas = {
        'processor': 'processSchema.json',
        'descriptor': 'descriptorSchema.json',
        'field': 'fieldSchema.json',
        'type': 'typeSchema.json',
    }

    if name not in schemas:
        raise ValueError()

    field_schema_file = finders.find('flow/{}'.format(schemas['field']), all=True)[0]
    with open(field_schema_file, 'r') as fn:
        field_schema = fn.read()

    if name == 'field':
        return json.loads(field_schema.replace('{{PARENT}}', ''))

    schema_file = finders.find('flow/{}'.format(schemas[name]), all=True)[0]
    with open(schema_file, 'r') as fn:
        schema = fn.read()

    return json.loads(schema.replace('{{FIELD}}', field_schema).replace('{{PARENT}}', '/field'))
890828
def validate_module_dir(dir)
      # first check to see if manifests directory even exists when path is nil
      if dir.nil?
        dir = '.'
      elsif dir.instance_of?(Array)
        puts 'Retrospec - an array of module paths is not supported at this time'.fatal
        raise Retrospec::Puppet::InvalidModulePathError
      end
      dir = File.expand_path(dir)
      manifest_dir = File.join(dir, 'manifests')
      if !File.exist?(manifest_dir)
        puts "No manifest directory in #{manifest_dir}, cannot validate this is a module".fatal
        raise Retrospec::Puppet::NoManifestDirError
      else
        files = Dir.glob("#{manifest_dir}/**/*.pp")
        warn "No puppet manifest files found at #{manifest_dir}".warning if files.length < 1
        # validate the manifest files, because if one files doesn't work it affects everything
        files.each do |file|
          begin
            parser.parse_file(file)
          rescue Puppet::ParseError
            puts "Manifest file: #{file} has parser errors, please fix and re-check using\n puppet parser validate #{file}".fatal
            raise Retrospec::Puppet::ParserError
          rescue SystemExit => e
            puts "Manifest file: #{file} has parser errors, please fix and re-check using\n puppet parser validate #{file}".fatal
            raise Retrospec::Puppet::ParserError
          end
        end
      end
      dir
    end
493584
public Schema loadSchema(String schema) {
    try {
      JSONObject rawSchema = new JSONObject(new JSONTokener(schema));
      return SchemaLoader.load(rawSchema);
    } catch (JSONException | SchemaException e) {
      throw new InvalidJsonSchemaException(e);
    }
  }
360008
private void loadManifest()
  {
    if (_isManifestRead)
      return;
    
    synchronized (this) {
      if (_isManifestRead)
        return;

      try {
        _manifest = _jarPath.getManifest();
        if (_manifest == null)
          return;

        Attributes attr = _manifest.getMainAttributes();
        if (attr != null)
          addManifestPackage("", attr);

        Map<String,Attributes> entries = _manifest.getEntries();

        for (Map.Entry<String,Attributes> entry : entries.entrySet()) {
          String pkg = entry.getKey();

          attr = entry.getValue();
          if (attr == null)
            continue;

          addManifestPackage(pkg, attr);
        }
      } catch (IOException e) {
        log.log(Level.WARNING, e.toString(), e);
      } finally {
        _isManifestRead = true;
      }
    }
  }
276613
def validate(schema):
    """"""
    try:
        tableschema.validate(schema)
        click.echo("Schema is valid")
        sys.exit(0)
    except tableschema.exceptions.ValidationError as exception:
        click.echo("Schema is not valid")
        click.echo(exception.errors)
        sys.exit(1)
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()
1183871
def register_schema(self, directory, path):
        
        self.schemas[path] = os.path.abspath(directory)
461387
def validate_schema(schema_name):
    """"""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            try:
                instance.validator(instance.schemas[schema_name]).validate(request.get_json())
            except ValidationError, e:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.BAD_SCHEMA,
                                                       e.message)
                instance.logger.error("Invalid Schema", ret_dict)
                return jsonify(ret_dict), 400
            instance.logger.debug("Schema is valid")
            return f(*args, **kw)
        return wrapper
    return decorator
1210668
private void validateSchemaWithFilePath(File schemaSourceFile, DataSchema schema)
  {
    if (schemaSourceFile != null && schemaSourceFile.isFile() && schema instanceof NamedDataSchema)
    {
      final NamedDataSchema namedDataSchema = (NamedDataSchema) schema;
      final String namespace = namedDataSchema.getNamespace();

      if (!FileUtil.removeFileExtension(schemaSourceFile.getName()).equalsIgnoreCase(namedDataSchema.getName()))
      {
        throw new IllegalArgumentException(namedDataSchema.getFullName() + " has name that does not match filename '" +
            schemaSourceFile.getAbsolutePath() + "'");
      }

      final String directory = schemaSourceFile.getParentFile().getAbsolutePath();
      if (!directory.endsWith(namespace.replace('.', File.separatorChar)))
      {
        throw new IllegalArgumentException(namedDataSchema.getFullName() + " has namespace that does not match " +
            "file path '" + schemaSourceFile.getAbsolutePath() + "'");
      }
    }
  }
209941
def validate(output, resource):
    '''
    
    '''
    try:
        import cerberus  # pylint: disable=import-error
    except ImportError:
        log.critical('You need module cerberus in order to use validation')
        return

    roots = __opts__['pepa_roots']

    valdir = os.path.join(roots['base'], resource, 'validate')

    all_schemas = {}
    pepa_schemas = []
    for fn in glob.glob(valdir + '/*.yaml'):
        log.info("Loading schema: %s", fn)
        with salt.utils.files.fopen(fn) as fhr:
            template = jinja2.Template(fhr.read())
        data = output
        data['grains'] = __grains__.copy()
        data['pillar'] = __pillar__.copy()
        schema = salt.utils.yaml.safe_load(template.render(data))
        all_schemas.update(schema)
        pepa_schemas.append(fn)

    val = cerberus.Validator()
    if not val.validate(output['pepa_keys'], all_schemas):
        for ekey, error in six.iteritems(val.errors):
            log.warning('Validation failed for key %s: %s', ekey, error)

    output['pepa_schema_keys'] = all_schemas
    output['pepa_schemas'] = pepa_schemas
109591
def validate(self, schema_str, xml_valid):
        
        # TODO: be able to get doc for error given an xsd.
        # Changed path to allow have xsd that are imported by others xsd in the
        # same library, and not call to SAT page each time that is generated
        # a new XML.
        with change_path():
            path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'templates')
            os.chdir(path)
            schema_root = etree.parse(StringIO(schema_str))
            schema = etree.XMLSchema(schema_root)
        try:
            tree = etree.parse(StringIO(xml_valid.encode('UTF-8')))
            schema.assertValid(tree)
        except etree.DocumentInvalid as ups:
            self.ups = ups
        finally:
            if self.ups:
                self.valid = False
            else:
                self.valid = True
            return self.valid
1124145
def validate_manifests(dist, attr, value):
    
    try:
        Manifest.normalize_manifests(value)
    except TypeError:
        raise distutils.errors.DistutilsSetupError(
            attr + "must be a mapping object like: {'package.name': "
            "sassutils.distutils.Manifest('sass/path')}, or as shorten form: "
            "{'package.name': ('sass/path', 'css/path'}), not " +
            repr(value),
        )
1318166
protected function loadManifest()
    {
        $manifestPath = Paths::assets('manifest.json');

        if (file_exists($manifestPath))
        {
            return json_decode(file_get_contents($manifestPath), true);
        }

        return null;
    }
991363
def get_schema_validator(self, schema_name):
        

        if schema_name not in self.schemas:
            schema_file = self.get_schema_file(schema_name)
            with open(schema_file) as f:
                try:
                    jsn_schema = json.load(f)
                except ValueError as ex:
                    log.error("Could not load %s", schema_file)
                    raise ex

            schemas_folder = self.get_schemas_folder()
            root_schema_path = self.get_schema_path(schemas_folder)
            resolver = jsonschema.RefResolver(root_schema_path, None)
            # cache the schema for future use
            self.schemas[schema_name] = (jsn_schema, resolver)
        else:
            jsn_schema, resolver = self.schemas[schema_name]

        validator = jsonschema.Draft4Validator(schema=jsn_schema, resolver=resolver)
        # validator.check_schema(jsn_schema) # check schema is valid

        return validator