Validates that the parameters on the JSON-RPC request match the types specified for
 this function

 Returns a JSON-RPC response hash if invalid, or nil if valid.

 * `req` - JSON-RPC request hash
 * `func` - Barrister::Function instance
323932
def validate_params(req, func)
      params = req["params"]
      if !params
        params = []
      end
      e_params  = func.params.length
      r_params  = params.length
      if e_params != r_params
        msg = "Function #{func.name}: Param length #{r_params} != expected length: #{e_params}"
        return err_resp(req, -32602, msg)
      end

      for i in (0..(e_params-1))
        expected = func.params[i]
        invalid = validate("Param[#{i}]", expected, expected["is_array"], params[i])
        if invalid != nil
          return err_resp(req, -32602, invalid)
        end
      end

      # valid
      return nil
    end
717955
function findMatchingExample(req, code, type) {
    const swagger = req.swagger.root;
    const responses = req.swagger.rel.responses;

    // if no responses then exit
    const responseKeys = responses && typeof responses === 'object' ? Object.keys(responses) : [];
    if (responseKeys.length === 0) return { code: 501, type: undefined };

    // get first code if not provided
    if (arguments.length < 1) code = responseKeys[0];

    // validate that responses exist
    const responseSchema = responses[code];
    if (!responseSchema) return { code: 501, type: undefined };

    const examples = responses[code].examples;
    const accept = type ?
        type :
        req.headers.hasOwnProperty('accept')
            ? req.headers.accept
            : Array.isArray(swagger.produces) && swagger.produces.length > 0
                ? swagger.produces[0]
                : examples && Object.keys(examples)[0];

    // check if there are examples
    const keys = examples ? Object.keys(examples) : [];
    const typesLength = keys.length;
    if (typesLength === 0) return { code: 501, type: undefined };

    // if anything is accepted then return first example
    if (accept === '*') return { code: code, type: keys[0] };

    // determine what types and subtypes are supported by examples
    const types = keys.map(key => {
        const ar = key.split('/');
        return { type: ar[0] || '*', subtype: ar[1] || '*' };
    });

    // find all the types that the client accepts
    const accepts = accept.split(/,\s*/);
    const length = accepts.length;
    for (let i = 0; i < length; i++) {

        // remove variable from type and separate type and subtype
        const item = accepts[i].split(';')[0];
        const parts = item.split('/');
        const a = {
            type: parts[0] || '*',
            subtype: parts[1] || '*'
        };

        // look for a match between types and accepts
        for (let j = 0; j < typesLength; j++) {
            const t = types[j];
            if ((t.type === '*' || a.type === '*' || a.type === t.type) &&
                (t.subtype === '*' || a.subtype === '*' || a.subtype === t.subtype)) return { code: code, type: keys[j] };
        }
    }

    return { code: 406, type: undefined };
}
919153
def post_json(path, object_to_post, response_type = nil)
      response_type = SimpleSolrClient::Response::GenericResponse if response_type.nil?
      response_type.new(_post_json(path, object_to_post))
    end
133930
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest:
    
    if args:
        kwargs['*args'] = args

    return rpcq.messages.RPCRequest(
        jsonrpc='2.0',
        id=str(uuid.uuid4()),
        method=method_name,
        params=kwargs
    )
1290966
def _validate_params(self, req):
        '''
        
        '''

        #does the method exist?
        method = req['method']
        if not method in self._methods:
            raise SLOJSONRPCError(-32601)
        fct = self._methods[method]['fct']

        #'id' is only needed for none SLOJSONRPCNotification's
        try:
            getattr(fct, '__SLOJSONRPCNotification__')
            if 'id' in req:
                logging.debug('JSONRPC: Fmt Error: no id for SLOJSONRPCNotifications')
                raise SLOJSONRPCError(-32602)
        except AttributeError:
            if not 'id' in req:
                logging.debug('JSONRPC: Fmt Error: Need an id for non SLOJSONRPCNotifications')
                raise SLOJSONRPCError(-32602)

        #get arguments and defaults for the python-function representing
        # the method
        argspec = self._methods[method]['argspec']
        args, defaults = list(argspec.args), \
            list(argspec.defaults if argspec.defaults else [])

        #ignore self and session
        if 'self' in args:
            args.remove('self')
        args.remove('session')

        #create required arguments. delete the ones with defaults
        required = list(args)
        if defaults:
            for default in defaults:
                required.pop()

        #check if we need paremeters and there are none, then error
        if len(required) > 0 and 'params' not in req:
            logging.debug('JSONRPC: Parameter Error: More than zero params required')
            raise SLOJSONRPCError(-32602)

        if 'params' in req:
            #parameters must be a dict if there is more then one
            if not isinstance(req['params'], dict) and len(required) > 1:
                logging.debug('JSONRPC: Parameter Error: "params" must be a dictionary')
                raise SLOJSONRPCError(-32602)

            if isinstance(req['params'], dict):
                #check if required parameters are there
                for key in required:
                    if not key in req['params']:
                        logging.debug('JSONRPC: Parameter Error: Required key "%s" is missing' % key)
                        raise SLOJSONRPCError(-32602)

                #check if parameters are given that do not exist in the method
                for key in req['params']:
                    if not key in required:
                        logging.debug('JSONRPC: Parameter Error: Key is not allowed "%s"' % key)
                        raise SLOJSONRPCError(-32602)
662574
def _prepare_response(retval)
      unless retval.is_a?(Hash)
        _error!(Errors::ServerError, "Invalid response: #{retval.inspect}")
      end

      JSON.dump(retval)
    end
867922
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:
    
    jsonschema_validate(request, schema)
    return request
346676
def matches?(code)
      path = 'http://test.host/redirect'

      unless @scope.respond_to?(:request) && @scope.respond_to?(:response)
        fail_spec_type and return false
      end
      unless ALLOWED_REQUEST_TYPES.include? @scope.request.class
        fail_request_type and return false
      end
      unless ALLOWED_RESPONSE_TYPES.include? @scope.response.class
        fail_response_type and return false
      end
      @scope.request.env['HTTP_REFERER'] ||= path
      unless code.is_a? Proc
        fail_input_type code and return false
      end
      code.call
      @response = @scope.response
      status_matcher = STATUS_CODE_MATCHER.new :redirect
      unless status_matcher.matches? @response
        fail_status_code status_matcher and return false
      end
      path_matcher = REDIRECT_PATH_MATCHER.new @scope, path
      unless path_matcher.matches? @response
        fail_redirect_path path_matcher and return false
      end
      true
    end
286325
function procRequest (type, schema, req, res, next) {
  const prcHttpCallOnError = this._prcHttpCallOnError
  const options = this._validationOptions

  Joi.validate(req[type], schema, options, validateRequest)

  function validateRequest (err, value) {
    return err
      ? prcHttpCallOnError
        ? res.status(400).send(err.message)
        : res.status(400) && next(err)
      : (req[type] = value) && next()
  }
}
1078726
def _validate_query_parameters(self, query, action_spec):
        
        processed_params = []
        for param_name, param_value in query.items():
            if param_name in action_spec['parameters'].keys():
                processed_params.append(param_name)

                # Check array
                if action_spec['parameters'][param_name]['type'] == 'array':
                    if not isinstance(param_value, list):  # Not an array
                        return False
                    else:
                        for i in param_value:  # Check type of all elements in array
                            if not self.check_type(i, action_spec['parameters'][param_name]['items']['type']):
                                return False

                elif not self.check_type(param_value, action_spec['parameters'][param_name]['type']):
                    return False

        # Check required
        if not all(param in processed_params for param, spec in action_spec['parameters'].items()
                   if spec['in'] == 'query' and 'required' in spec and spec['required']):
            return False
        return True
1258332
function validateJSONResponse(resp, result_schema) {

   const ajv = new Ajv();
   if (result_schema) {
      try {
         const valid = ajv.validate(result_schema, resp);
         assert(valid);
         return resp;
      }
      catch(e) {
         try {
            // error message
            const valid = ajv.validate(CORE_ERROR_SCHEMA, resp);
            assert(valid);
            return resp;
         }
         catch(e2) {
            console.log("Failed to validate with desired schema");
            console.log(e.stack);
            console.log("Failed to validate with error schema");
            console.log(e2.stack);
            console.log("Desired schema:");
            console.log(result_schema);
            console.log("Parsed message:");
            console.log(resp);
            throw new Error("Invalid core message");
         }
      }
   }
   else {
      return resp;
   }
}
997910
def validate_api_response(schema, raw_response, request_method='get', raw_request=None):
    
    request = None
    if raw_request is not None:
        request = normalize_request(raw_request)

    response = None
    if raw_response is not None:
        response = normalize_response(raw_response, request=request)

    if response is not None:
        validate_response(
            response=response,
            request_method=request_method,
            schema=schema
        )
397821
function validate(args, required) {
    var result = {
      error: false,
      message: 'No errors'
    }

    // ensure required properties were passed in the arguments hash
    if (required) {
      var keys = _.keys(args);
      required.forEach(function(field) {
        if(!_.contains(keys, field)) {
          result.error = true;
          result.message = 'The following values must be passed: ' + required.join(', ');
        }
      })
    }

    return result;

  }
1214266
def validate(key):
    
    if not isinstance(key, (str, bytes)):
        raise KeyError('Key must be of type str or bytes, found type {}'.format(type(key)))
884795
def validate(instance):
    

    jsonschema.validate(
        to_dict(instance, dict_type=dict), build_schema(instance.__class__)
    )
1258890
def validate_filter(self, key, filter_value):
        
        ok = False
        seek = u"filter[%s]" % key
        value = None
        for link in self.schema['links']:
            if link['rel'] == 'instances':
               for property in link['properties']:
                   if seek == property:
                       value = link['properties'][property]
                       ok = True
        if not ok:
            return False
        ok = self._is_type(filter_value, value['type'])
        # if string with type add validation
        if ok is True and value['type'] == 'string' and 'format' in value.keys():
            ok = self._validate_json_format(filter_value, value)
            
        return ok
536593
def json_or_jsonp(func):
    """"""
    @wraps(func)
    def _(*args, **kwargs):
        mimetype = 'application/javascript'
        callback = request.args.get('callback', None)
        if callback is None:
            content = func(*args, **kwargs)

        else:
            content = "%s(%s)" % (callback, func(*args, **kwargs))
        return current_app.response_class(content, mimetype=mimetype)
    return _