Loads and verifies metadata.

    Args:
      submission_type: type of the submission

    Returns:
      dictionaty with metadata or None if metadata not found or invalid
196269
def _load_and_verify_metadata(self, submission_type):
    
    metadata_filename = os.path.join(self._extracted_submission_dir,
                                     'metadata.json')
    if not os.path.isfile(metadata_filename):
      logging.error('metadata.json not found')
      return None
    try:
      with open(metadata_filename, 'r') as f:
        metadata = json.load(f)
    except IOError as e:
      logging.error('Failed to load metadata: %s', e)
      return None
    for field_name in REQUIRED_METADATA_JSON_FIELDS:
      if field_name not in metadata:
        logging.error('Field %s not found in metadata', field_name)
        return None
    # Verify submission type
    if submission_type != metadata['type']:
      logging.error('Invalid submission type in metadata, expected "%s", '
                    'actual "%s"', submission_type, metadata['type'])
      return None
    # Check submission entry point
    entry_point = metadata['entry_point']
    if not os.path.isfile(os.path.join(self._extracted_submission_dir,
                                       entry_point)):
      logging.error('Entry point not found: %s', entry_point)
      return None
    if not entry_point.endswith('.sh'):
      logging.warning('Entry point is not an .sh script. '
                      'This is not necessarily a problem, but if submission '
                      'won''t run double check entry point first: %s',
                      entry_point)
    # Metadata verified
    return metadata
1211797
def validate(metadata):
        
        # validate required sections and their sub items
        for section_key in Metadata.REQUIRED_SECTIONS:
            if section_key not in metadata or not metadata[section_key] or not isinstance(
                    metadata[section_key], dict):
                return False

            section = Metadata.MAIN_SECTIONS[section_key]
            section_metadata = metadata[section_key]
            for subkey in section.REQUIRED_VALUES_KEYS:
                if subkey not in section_metadata or section_metadata[subkey] is None:
                    return False

        return True
1155527
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None:
    
    for key, value in meta.items():
        if key in META_FIELDS:
            if type(value) is not META_FIELDS[key]:
                raise ValidationError(
                    f"Values for {key} are expected to have the type {META_FIELDS[key]}, "
                    f"instead got {type(value)}."
                )
        elif allow_extra_meta_fields:
            if key[:2] != "x-":
                raise ValidationError(
                    "Undefined meta fields need to begin with 'x-', "
                    f"{key} is not a valid undefined meta field."
                )
        else:
            raise ValidationError(
                f"{key} is not a permitted meta field. To allow undefined fields, "
                "set `allow_extra_meta_fields` to True."
            )
1015556
def post_verification_collection_with_http_info(request)
      raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest

      @api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
      # verify the required parameter 'name' is set
      raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil?
      # resource path
      local_var_path = '/signature/{name}/collection/verification'
      local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s)

      # query parameters
      query_params = {}
      if local_var_path.include? ('{' + downcase_first_letter('Password') + '}')
        local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s)
      else
        query_params[downcase_first_letter('Password')] = request.password unless request.password.nil?
      end
      if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}')
        local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s)
      else
        query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil?
      end
      if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}')
        local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s)
      else
        query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil?
      end

      # header parameters
      header_params = {}
      # HTTP header 'Accept' (if needed)
      header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
      # HTTP header 'Content-Type'
      header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])

      # form parameters
      form_params = {}

      # http body (model)
      post_body = @api_client.object_to_http_body(request.verify_options_collection_data)
      data, status_code, headers = @api_client.call_api(:POST, local_var_path,
                                                        header_params: header_params,
                                                        query_params: query_params,
                                                        form_params: form_params,
                                                        body: post_body,
                                                        access_token: get_access_token,
                                                        return_type: 'VerifiedDocumentResponse')
      if @api_client.config.debugging
        @api_client.config.logger.debug "API called:
        SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
      end
      [data, status_code, headers]
    end
745207
def format_content_type(repo, content_type):
    
    storage_manager = StorageManager(repo)
    model_class = load_model_class(repo, content_type)
    return [dict(model_obj)
            for model_obj in storage_manager.iterate(model_class)]
1149461
def format_content_type_object(repo, content_type, uuid):
    
    try:
        storage_manager = StorageManager(repo)
        model_class = load_model_class(repo, content_type)
        return dict(storage_manager.get(model_class, uuid))
    except GitCommandError:
        raise NotFound('Object does not exist.')
72068
def _load_meta(self, meta):
        ''''''
        meta = yaml.load(meta, Loader=Loader)

        # Versions are often specified in a format that is convertible to an
        # int or a float, so we want to make sure it is interpreted as a str.
        # Fix for the bug #300.
        if 'version' in meta:
            meta['version'] = str(meta['version'])

        return meta
1126645
def validate_type(self, type_):
        
        if type_ is not None and type_ not in self.types_set:
            raise ValueError('Invalid type for %s:%s' % (self.__class__, type_))
527774
def get_upload_key_metadata(self):
        """"""
        key = self.get_upload_key()
        metadata = key.metadata.copy()

        # Some http header properties which are stored on the key need to be
        # copied to the metadata when updating
        headers = {
            # http header name, key attribute name
            'Cache-Control': 'cache_control',
            'Content-Type': 'content_type',
            'Content-Disposition': 'content_disposition',
            'Content-Encoding': 'content_encoding',
        }

        for header_name, attribute_name in headers.items():
            attribute_value = getattr(key, attribute_name, False)
            if attribute_value:
                metadata.update({b'{0}'.format(header_name):
                                 b'{0}'.format(attribute_value)})
        return metadata
896398
def load_model_class(repo, content_type):
    
    schema = get_schema(repo, content_type).to_json()
    return deserialize(schema, module_name=schema['namespace'])
728257
def load_and_validate(document_loader,                 # type: Loader
                      avsc_names,                      # type: Names
                      document,                        # type: Union[CommentedMap, Text]
                      strict,                          # type: bool
                      strict_foreign_properties=False  # type: bool
                      ):
    # type: (...) -> Tuple[Any, Dict[Text, Any]]
    
    try:
        if isinstance(document, CommentedMap):
            data, metadata = document_loader.resolve_all(
                document, document["id"], checklinks=True,
                strict_foreign_properties=strict_foreign_properties)
        else:
            data, metadata = document_loader.resolve_ref(
                document, checklinks=True,
                strict_foreign_properties=strict_foreign_properties)

        validate_doc(avsc_names, data, document_loader, strict,
                     strict_foreign_properties=strict_foreign_properties)

        return data, metadata
    except validate.ValidationException as exc:
        raise validate.ValidationException(strip_dup_lineno(str(exc)))
50435
def post(self, request, **resources):
        
        if not self._meta.form:
            return None

        form = self._meta.form(request.data, **resources)
        if form.is_valid():
            return form.save()

        raise FormError(form)
253568
async def Save(self, metadata):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='ImageMetadata',
                   request='Save',
                   version=2,
                   params=_params)
        _params['metadata'] = metadata
        reply = await self.rpc(msg)
        return reply
1273849
def metadata(request, config_loader_path=None, valid_for=None):
    
    conf = get_config(config_loader_path, request)
    metadata = entity_descriptor(conf)
    return HttpResponse(content=text_type(metadata).encode('utf-8'),
                        content_type="text/xml; charset=utf8")
307886
def validate_metadata_token(self, claims, endpoint):
        
        self._grant_types.extend(endpoint._grant_types.keys())
        claims.setdefault("token_endpoint_auth_methods_supported", ["client_secret_post", "client_secret_basic"])

        self.validate_metadata(claims, "token_endpoint_auth_methods_supported", is_list=True)
        self.validate_metadata(claims, "token_endpoint_auth_signing_alg_values_supported", is_list=True)
        self.validate_metadata(claims, "token_endpoint", is_required=True, is_url=True)
1154586
def get_submission(self, submissionid, user_check=True):
        
        sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)})
        if user_check and not self.user_is_submission_owner(sub):
            return None
        return sub
940035
def load_query_string_data(request_schema, query_string_data=None):
    
    if query_string_data is None:
        query_string_data = request.args

    request_data = request_schema.load(query_string_data)
    if request_data.errors:
        # pass the validation errors back in the context
        raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors))
    return request_data.data