If the Swagger Path was matched, but the HTTP method doesn't match any of the Swagger Operations,
then an HTTP 405 (Method Not Allowed) error is thrown, and the "Allow" header is set to the list of valid methods
10907
function http405 (req, res, next) {
  if (req.swagger && req.swagger.path && !req.swagger.operation) {
    util.debug(
      'Client attempted a %s operation on "%s", which is not allowed by the Swagger API. ' +
      "Returning HTTP 405 (Method Not Allowed)",
      req.method, req.path
    );

    // Let the client know which methods are allowed
    let allowedList = util.getAllowedMethods(req.swagger.path);
    res.set("Allow", allowedList);

    throw ono({ status: 405 }, "%s does not allow %s. \nAllowed methods: %s",
      req.path, req.method, allowedList || "NONE");
  }

  next();
}
119491
def call_api(path, params = {})
      raise ArgumentError, 'You must include an HTTP method' unless params[:method]
      raise InvalidConnection, 'You have not authenticated and have no token' unless @token
      headers = {
        'Content-Type' => 'application/json',
        'Authorization' => "Bearer #{@token}"
      }
      headers.merge!(params[:headers]) if params[:headers]

      arguments = {headers: headers}
      arguments.merge!({body: params[:body].to_json}) if params[:body]
      arguments.merge!({query: params[:query]}) if params[:query]

      HTTParty.send params[:method], url(path), arguments
    end
585658
private <TResponse> TResponse callServiceOwnerPostApi(
            String path, Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callServiceOwnerPostApi(path, (Map<String, String>)null, requestBody, responseClass);
    }
98855
def request(method, path, opts = {})
      raise ClientError, 'Access token missing' unless @access_token

      opts[:headers] = {} if opts[:headers].nil?
      opts[:headers]['Accept'] = 'application/json'
      opts[:headers]['Content-Type'] = 'application/json' unless method == :get
      opts[:headers]['User-Agent'] = user_agent
      opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil?
      path = URI.encode(path)

      # Reset the URL in case the environment / base URL has been changed.
      @oauth_client.site = base_url

      header_keys = opts[:headers].keys.map(&:to_s)
      if header_keys.map(&:downcase).include?('authorization')
        @oauth_client.request(method, path, opts)
      else
        @access_token.send(method, path, opts)
      end
    rescue OAuth2::Error => err
      raise GoCardless::ApiError.new(err.response)
    end
293304
def handle_not_allowed(environ, start_response):
    
    _methods = util.wsgi_path_item(environ, '_methods')
    headers = {}
    if _methods:
        headers['allow'] = str(_methods)
    raise webob.exc.HTTPMethodNotAllowed(
        ('The method specified is not allowed for this resource.'),
        headers=headers, json_formatter=util.json_error_formatter)
1059471
function processResponses(swagger, def, path, models) {
  var responses = def.responses || {};
  var operationResponses = {};
  operationResponses.returnHeaders = false;
  for (var code in responses) {
    var response = responses[code];
    if (response.$ref) {
      response = resolveRef(swagger, response.$ref);
    }
    if (!response.schema) {
      continue;
    }
    var type = propertyType(response.schema);
    if (/2\d\d/.test(code)) {
      // Successful response
      operationResponses.resultType = type;
      operationResponses.resultDescription = response.description;
      var headers = response.headers || {};
      for (var prop in headers) {
        // This operation returns at least one header
        operationResponses.returnHeaders = true;
        break;
      }
    }
    operationResponses[code] = {
      code: code,
      type: type,
    };
  }
  if (!operationResponses.resultType) {
    operationResponses.resultType = 'null';
  }
  return operationResponses;
}
367658
def allowed_methods(self, path_info=None):
        
        try:
            self.match(path_info, method="--")
        except MethodNotAllowed as e:
            return e.valid_methods
        except HTTPException:
            pass
        return []
361716
function requestMetadata (context, router) {
  router = router || context.router;

  return [
    swaggerMetadata,
    swaggerApiMetadata,
    swaggerPathMetadata,
    swaggerOperationMetadata,
    swaggerParamsMetadata,
    swaggerSecurityMetadata
  ];

  /**
   * Sets `req.swagger.api`
   */
  function swaggerApiMetadata (req, res, next) {
    // Only set req.swagger.api if the request is under the API's basePath
    if (context.api) {
      let basePath = util.normalizePath(context.api.basePath, router);
      let reqPath = util.normalizePath(req.path, router);
      if (_.startsWith(reqPath, basePath)) {
        req.swagger.api = context.api;
      }
    }

    next();
  }

  /**
   * Sets `req.swagger.path`
   */
  function swaggerPathMetadata (req, res, next) {
    if (req.swagger.api) {
      let relPath = getRelativePath(req);
      let relPathNormalized = util.normalizePath(relPath, router);

      // Search for a matching path
      Object.keys(req.swagger.api.paths).some((swaggerPath) => {
        let swaggerPathNormalized = util.normalizePath(swaggerPath, router);

        if (swaggerPathNormalized === relPathNormalized) {
          // We found an exact match (i.e. a path with no parameters)
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
          return true;
        }
        else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) {
          // We found a possible match, but keep searching in case we find an exact match
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
        }
      });

      if (req.swagger.path) {
        util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName);
      }
      else {
        util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path);
      }
    }

    next();
  }
}
865069
private String checkRequestMethod(HttpServletRequest request, JCorsConfig config) {

		String requestMethod = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD_HEADER);
		Constraint.ensureNotEmpty(requestMethod, "Request Method Header must be supplied");

		Constraint.ensureTrue(config.isMethodAllowed(requestMethod),
				String.format("The specified method is not allowed: '%s'", requestMethod));

		return requestMethod;
	}
522052
void doMethod(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) {

        // Locate a request handler:
        String requestPath = mapRequestPath(request);
        Route route = api.get(requestPath);

        try {

            if (route != null && route.requestHandlers.containsKey(httpMethod)) {
                handleRequest(request, response, route, httpMethod);
            } else {
                handleNotFound(request, response);
            }

        } catch (Throwable t) {

            // Chances are the exception we've actually caught is the reflection
            // one from Method.invoke(...)
            Throwable caught = t;
            if (InvocationTargetException.class.isAssignableFrom(t.getClass())) {
                caught = t.getCause();
            }

            RequestHandler requestHandler = (route == null ? null : route.requestHandlers.get(httpMethod));
            handleError(request, response, requestHandler, caught);
        }

    }
374231
protected String registerParameters(Swagger swagger, Operation operation, Route route, Method method) {
        Map<String, Object> pathParameterPlaceholders = new HashMap<>();
        for (String uriParameterName : getUriParameterNames(route.getUriPattern())) {
            // path parameters are required
            PathParameter pathParameter = new PathParameter();
            pathParameter.setName(uriParameterName);
            setPropertyType(swagger, pathParameter, method);
            pathParameter.setRequired(true);

            operation.addParameter(pathParameter);

            pathParameterPlaceholders.put(uriParameterName, "{" + uriParameterName + "}");
        }

        // identify body, header, query, & form parameters
        for (Parameter methodParameter : method.getParameters()) {

            String methodParameterName = getParameterName(methodParameter);

            if (pathParameterPlaceholders.containsKey(methodParameterName)) {
                // path parameter already accounted for
                continue;
            }

            if (methodParameter.isAnnotationPresent(Local.class)) {
                // ignore parameter
                continue;
            }

            if (methodParameter.isAnnotationPresent(Session.class)) {
                // ignore parameter
                continue;
            }

            if (methodParameter.isAnnotationPresent(Auth.class)) {
                // ignore parameter
                continue;
            }

            if (methodParameter.isAnnotationPresent(Body.class)) {

                // BODY
                BodyParameter bodyParameter = new BodyParameter();
                bodyParameter.setName(methodParameterName);
                bodyParameter.setDescription(getDescription(methodParameter));
                bodyParameter.setRequired(true);

                if (methodParameter.getType().isArray()) {
                    // ARRAY []
                    Property property = getSwaggerProperty(swagger, methodParameter.getType().getComponentType());
                    ArrayModel arrayModel = new ArrayModel();
                    arrayModel.setItems(property);
                    bodyParameter.setSchema(arrayModel);
                } else if (Collection.class.isAssignableFrom(methodParameter.getType())) {
                    // COLLECTION
                    Class<?> componentClass = ClassUtil.getParameterGenericType(method, methodParameter);
                    Property property = getSwaggerProperty(swagger, componentClass);
                    ArrayModel arrayModel = new ArrayModel();
                    arrayModel.setItems(property);
                    bodyParameter.setSchema(arrayModel);
                } else {
                    // OBJECT
                    Property property = getSwaggerProperty(swagger, methodParameter.getType());
                    if (property instanceof RefProperty) {
                        // Domain Model
                        RefProperty ref = (RefProperty) property;
                        bodyParameter.setSchema(new RefModel(ref.getSimpleRef()));
                    } else {
                        // Primitive Type
                        ModelImpl model = new ModelImpl();
                        model.setType(property.getType());
                        model.setFormat(property.getFormat());
                        bodyParameter.setSchema(model);
                    }
                }

                operation.addParameter(bodyParameter);

            } else if (methodParameter.isAnnotationPresent(Header.class)) {

                // HEADER
                Header header = methodParameter.getAnnotation(Header.class);
                HeaderParameter headerParameter = new HeaderParameter();
                if (Strings.isNullOrEmpty(header.value())) {
                    headerParameter.setName(methodParameterName);
                } else {
                    headerParameter.setName(header.value());
                }

                headerParameter.setDescription(getDescription(methodParameter));
                setPropertyType(swagger, headerParameter, method);

                operation.addParameter(headerParameter);

            } else if (methodParameter.isAnnotationPresent(Form.class) || FileItem.class == methodParameter.getType()) {

                // FORM
                FormParameter formParameter = new FormParameter();
                formParameter.setName(methodParameterName);
                formParameter.setDescription(getDescription(methodParameter));
                setPropertyType(swagger, formParameter, method);

                operation.addParameter(formParameter);

                if (FileItem.class == methodParameter.getType()) {
                    // if we see a FileItem, then this MUST be a multipart POST
                    operation.setConsumes(Arrays.asList(HttpConstants.ContentType.MULTIPART_FORM_DATA));
                } else if (!operation.getConsumes().contains(HttpConstants.ContentType.MULTIPART_FORM_DATA)) {
                    // only override consumes if this is NOT a multipart POST
                    operation.setConsumes(Arrays.asList(HttpConstants.ContentType.APPLICATION_FORM_URLENCODED));
                }

            } else {

                // QUERY
                QueryParameter queryParameter = new QueryParameter();
                queryParameter.setName(methodParameterName);
                queryParameter.setDescription(getDescription(methodParameter));
                setPropertyType(swagger, queryParameter, method);

                operation.addParameter(queryParameter);
            }

        }

        // we need to rewrite the uripattern without regex for Swagger
        // e.g. /employee/{id: 0-9+} must be rewritten as /employee/{id}
        String swaggerUri = router.uriFor(route.getUriPattern(), pathParameterPlaceholders);
        return swaggerUri;
    }
415470
function validateStructure (apiDefinition) {
  var results = helpers.validateAgainstSchema(helpers.getJSONSchemaValidator(),
                                              swaggerSchema,
                                              apiDefinition.definitionFullyResolved);

  // Make complex JSON Schema validation errors easier to understand (Issue 15)
  results.errors = results.errors.map(function (error) {
    var defType = ['additionalProperties', 'items'].indexOf(error.path[error.path.length - 1]) > -1 ?
          'schema' :
          error.path[error.path.length - 2];

    if (['ANY_OF_MISSING', 'ONE_OF_MISSING'].indexOf(error.code) > -1) {
      switch (defType) {
      case 'parameters':
        defType = 'parameter';
        break;

      case 'responses':
        defType = 'response';
        break;

      case 'schema':
        defType += ' ' + error.path[error.path.length - 1];

        // no default
      }

      error.message = 'Not a valid ' + defType + ' definition';
    }

    return error;
  });

  // Treat invalid/missing references as structural errors
  _.each(apiDefinition.references, function (refDetails, refPtr) {
    var refPath = JsonRefs.pathFromPtr(refPtr);
    var err;

    if (refDetails.missing) {
      err = {
        code: 'UNRESOLVABLE_REFERENCE',
        message: 'Reference could not be resolved: ' + refDetails.uri,
        path: refPath.concat('$ref')
      };

      if (_.has(refDetails, 'error')) {
        err.error = refDetails.error;
      }

      results.errors.push(err);
    } else if (refDetails.type === 'invalid') {
      results.errors.push({
        code: 'INVALID_REFERENCE',
        message: refDetails.error || 'Invalid JSON Reference',
        path: refPath.concat('$ref')
      });
    } else if (_.has(refDetails, 'warning')) {
      // json-refs only creates warnings for JSON References with superfluous properties which will be ignored
      results.warnings.push({
        code: 'EXTRA_REFERENCE_PROPERTIES',
        message: refDetails.warning,
        path: refPath
      });
    }
  });

  return results;
}
1134434
public PactDslRequestWithPath matchHeader(String header, String regex, String headerExample) {
        requestMatchers.addCategory("header").setRule(header, new RegexMatcher(regex));
        requestHeaders.put(header, Collections.singletonList(headerExample));
        return this;
    }
791841
function http413 (req, res, next) {
  if (util.isSwaggerRequest(req)) {
    // Determine if the request allows body content
    let bodyAllowed = req.swagger.params.some((param) => {
      return param.in === "body" || param.in === "formData";
    });

    if (!bodyAllowed) {
      // NOTE: We used to also check the Transfer-Encoding header, but that fails in Node 0.10.x
      // TODO: Once we drop support for Node 0.10.x, add a Transfer-Encoding check (via typeIs.hasBody())
      let length = req.get("Content-Length");
      util.debug("Validating Content-Length header (%d)", length);

      // NOTE: Even a zero-byte file attachment will have a Content-Length > 0
      if (length > 0) {
        util.debug(
          'The HTTP request contains body content, but the %s operation on "%s" does not allow a request body. ' +
          "Returning HTTP 413 (Request Entity Too Large)",
          req.method, req.path
        );
        throw ono({ status: 413 }, "%s %s does not allow body content", req.method, req.path);
      }
    }
  }

  next();
}
1151153
private void handleEndpointMatch(OngoingRequest request, RuleMatch<Endpoint> match) {
    final Endpoint endpoint = match.getRule().getTarget();
    final Map<String, String> parsedPathArguments = match.parsedPathArguments();
    final Client requestScopedClient = client.wrapRequest(request.request());
    final RequestContext requestContext =
        RequestContexts.create(request.request(),
                               requestScopedClient,
                               parsedPathArguments,
                               request.arrivalTimeNanos(),
                               request.metadata());

    erf.create(request, requestContext, endpoint)
        .run();
  }
1281967
function Router_process(method, parsedUrl, headers) {

        return this.parseRequest(method, parsedUrl, headers)
            .then(function (routeRule) {
                if (Type.isArray(routeRule) && routeRule.length === 2) {
                    return Promise.resolve(routeRule);
                }
                // only on not found throw an error 404
                throw new error.HttpError(404, core.toObject(routeRule), 'Not found');
            }, function (e) {
                throw new error.HttpError(500, {}, 'Not found', e);
            });
    }
652830
function swaggerPathMetadata (req, res, next) {
    if (req.swagger.api) {
      let relPath = getRelativePath(req);
      let relPathNormalized = util.normalizePath(relPath, router);

      // Search for a matching path
      Object.keys(req.swagger.api.paths).some((swaggerPath) => {
        let swaggerPathNormalized = util.normalizePath(swaggerPath, router);

        if (swaggerPathNormalized === relPathNormalized) {
          // We found an exact match (i.e. a path with no parameters)
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
          return true;
        }
        else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) {
          // We found a possible match, but keep searching in case we find an exact match
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
        }
      });

      if (req.swagger.path) {
        util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName);
      }
      else {
        util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path);
      }
    }

    next();
  }