If the request is under the Swagger API's basePath, but no matching Path was found,
then an HTTP 404 (Not Found) error is thrown
165413
function http404 (req, res, next) {
  if (req.swagger && req.swagger.api && !req.swagger.path) {
    util.debug(
      'Client requested path "%s", which is not defined in the Swagger API. Returning HTTP 404 (Not Found)',
      req.path
    );
    throw ono({ status: 404 }, "Resource not found: %s", req.path);
  }

  next();
}
1338215
def current_crumb?(path, pattern = :inclusive)
      return false unless request.get? || request.head?

      origin_path = URI.parser.unescape(path).force_encoding(Encoding::BINARY)

      request_uri = request.fullpath
      request_uri = URI.parser.unescape(request_uri)
      request_uri.force_encoding(Encoding::BINARY)

      # strip away trailing slash
      if origin_path.start_with?('/') && origin_path != '/'
        origin_path.chomp!('/')
        request_uri.chomp!('/')
      end

      if %r{^\w+://} =~ origin_path
        origin_path.chomp!('/')
        request_uri.insert(0, "#{request.protocol}#{request.host_with_port}")
      end

      case pattern
      when :inclusive
        !request_uri.match(/^#{Regexp.escape(origin_path)}(\/.*|\?.*)?$/).nil?
      when :exclusive
        !request_uri.match(/^#{Regexp.escape(origin_path)}\/?(\?.*)?$/).nil?
      when :exact
        request_uri == origin_path
      when :force
        true
      when Regexp
        !request_uri.match(pattern).nil?
      when Hash
        query_params = URI.encode_www_form(pattern)
        !request_uri.match(/^#{Regexp.escape(origin_path)}\/?(\?.*)?.*?#{query_params}.*$/).nil?
      else
        raise ArgumentError, "Unknown `:#{pattern}` match option!"
      end
    end
538621
function buildPath (basePath, queryParams) {
    basePath = basePath.concat('?')
    var url = basePath.concat(queryString.stringify(queryParams))
    return url
  }
978483
def add_swagger(app, json_route, html_route):
    
    app.router.add_route('GET', json_route, create_swagger_json_handler(app))
    add_swagger_api_route(app, html_route, json_route)
140792
public void route(HttpMethods meth, String path, API api, GwCode code) throws Exception {
		String version = "1.0";
		// Get Correct API Class from Mapper
		Class<?> respCls = facade.mapper().getClass(api); 
		if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
		// setup Application API HTML ContentTypes for JSON and Route
		String application = applicationJSON(respCls, version);
		//route(env,meth,path,code,application,"application/json;version="+version,"*/*");

		// setup Application API HTML ContentTypes for XML and Route
		application = applicationXML(respCls, version);
		//route(env,meth,path,code.clone(facade_1_0_XML,false),application,"text/xml;version="+version);
		
		// Add other Supported APIs here as created
	}
293134
def find_matching_middleware(self, method, path):
        
        for mw in self.mw_list:
            if not mw.matches_method(method):
                continue

            # get the path matching this middleware and the 'rest' of the url
            # (i.e. the part that comes AFTER the match) to be potentially
            # matched later by a subchain
            path_match, rest_url = mw.path_split(path)
            if self.should_skip_middleware(mw, path_match, rest_url):
                continue

            yield mw, path_match, rest_url
1175303
function parseSwagger(swagger) {
  const { paths, components, info, servers, security } = swagger;
  const api = {};

  for (const path in paths) {
    for (const method in paths[path]) {
      const {
        operationId,
        summary,
        tags,
        parameters,
        requestBody,
        responses,
        security,
      } = paths[path][method];

      // make sure some props must exist
      if (!operationId)
        throw new Error(`missing operationId for ${method} ${path}`);
      if (!tags && !tags[0])
        throw new Error(`missing operation tag for ${method} ${path}`);

      // camelcase operationId
      const name = camelCase(operationId);

      // use 200/204 response, use http-errors as error responses. https://github.com/jshttp/http-errors
      const res200 = responses["200"] || responses[200];
      const res201 = responses["201"] || responses[201];
      const res202 = responses["202"] || responses[202];
      const res204 = responses["204"] || responses[204];
      const response = res200 || res201 || res202 || res204;
      if (!response)
        throw new Error(`missing 20X response for ${method} ${path}`);

      if (res200) {
        response.status = 200;
        response.content = get(response, ["content", "application/json"]);
      }

      if (res201) {
        response.status = 201;
        response.content = get(response, ["content", "application/json"]);
      }

      if (res202) {
        response.status = 202;
        response.content = get(response, ["content", "application/json"]);
      }

      if (res204) {
        response.status = 204;
        response.content = get(response, ["content", "application/json"]);
      }

      // requestBody
      if (requestBody) {
        requestBody.content = get(requestBody, ["content", "application/json"]);
      }

      // use tags[0] as api's name
      api[tags[0]] = api[tags[0]] || { name: tags[0], operations: [], ref: [] };

      api[tags[0]].operations.push({
        method,
        name,
        operationId,
        parameters,
        path,
        requestBody,
        response,
        summary,
        security,
      });
    }
  }

  return { info, servers, api, components, security };
}
392335
def route_not_found(*args):
        
        response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION)
        return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403)
832491
def add_paths(paths, base_path, operations):
    
    for operation, ns, rule, func in operations:
        path = build_path(operation, ns)
        if not path.startswith(base_path):
            continue
        method = operation.value.method.lower()
        # If there is no version number or prefix, we'd expect the base path to be ""
        # However, OpenAPI requires the minimal base path to be "/"
        # This means we need branching logic for that special case
        suffix_start = 0 if len(base_path) == 1 else len(base_path)
        paths.setdefault(
            path[suffix_start:],
            swagger.PathItem(),
        )[method] = build_operation(operation, ns, rule, func)
1248926
function getRelativePath (req) {
  if (!req.swagger.api.basePath) {
    return req.path;
  }
  else {
    return req.path.substr(req.swagger.api.basePath.length);
  }
}
365103
@Override
    @Path("/{requestId}")
    @ApiOperation(value="Retrieve a request or a page of requests according to specified filters",
        notes="If requestId is not present, returns all matching requests.",
        response=Request.class, responseContainer="List")
    public JSONObject get(String path, Map<String,String> headers)
    throws ServiceException, JSONException {
        RequestServices requestServices = ServiceLocator.getRequestServices();
        try {
            Query query = getQuery(path, headers);
            String segOne = getSegment(path, 1);
            if (segOne != null) {
                if (segOne.equals("tops")) {
                    return getTops(query).getJson();
                }
                else if (segOne.equals("breakdown")) {
                    return getBreakdown(query).getJson();
                }
                else if (segOne.equals("paths")) {
                    return getPaths(query).getJson();
                }
                else if (segOne.equals("insights")) {
                    JsonList<Insight> jsonList = getInsights(query);
                    JSONObject json = jsonList.getJson();
                    String trend = query.getFilter("trend");
                    if ("completionTime".equals(trend)) {
                        List<Timepoint> timepoints = requestServices.getRequestTrend(query);
                        json.put("trend", new JsonList<>(timepoints, "trend").getJson().getJSONArray("trend"));
                    }
                    return json;
                }
                else {
                    try {
                        if (query.getBooleanFilter("master")) {
                            String masterRequestId = segOne;
                            if (query.getBooleanFilter("response")) {
                                Request masterRequest = requestServices.getMasterRequestResponse(masterRequestId);
                                if (masterRequest == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Master request not found: " + masterRequestId);
                                return masterRequest.getJson();
                            }
                            else {
                                Request masterRequest = requestServices.getMasterRequest(masterRequestId);
                                if (masterRequest == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Master request not found: " + masterRequestId);
                                return masterRequest.getJson();
                            }
                        }
                        else {
                            Long requestId = Long.valueOf(segOne);
                            if (query.getBooleanFilter("request") && query.getBooleanFilter("response")) {
                                Request request = requestServices.getRequestAndResponse(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                            else if (query.getBooleanFilter("response")) {
                                Request request = requestServices.getRequestResponse(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                            else {
                                Request request = requestServices.getRequest(requestId);
                                if (request == null)
                                    throw new ServiceException(ServiceException.NOT_FOUND, "Request not found: " + requestId);
                                return request.getJson();
                            }
                        }
                    }
                    catch (NumberFormatException ex) {
                        throw new ServiceException(ServiceException.BAD_REQUEST, "Bad requestId: " + segOne);
                    }
                }
            }
            else {
                if (query.getLongFilter("ownerId") >= 0L) {
                    RequestList reqList = requestServices.getRequests(query);
                    if (!reqList.getItems().isEmpty())
                        return requestServices.getRequestAndResponse(reqList.getItems().get(0).getId()).getJson();
                    else
                        throw new ServiceException(ServiceException.NOT_FOUND, "Request not found for ownerId: " + query.getLongFilter("ownerId"));
                }
                else
                    return requestServices.getRequests(query).getJson();
            }
        }
        catch (ServiceException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
        }
    }
925216
def find_resource_paths(schema_dir):
    
    def not_api_doc_file(filename):
        return not filename.endswith(API_DOCS_FILENAME)

    def not_swagger_dot_json(filename):
        # Exclude a Swagger 2.0 schema file if it happens to exist.
        return not os.path.basename(filename) == 'swagger.json'

    def filename_to_path(filename):
        filename, _ext = os.path.splitext(os.path.basename(filename))
        return '/' + filename

    filenames = glob.glob('{0}/*.json'.format(schema_dir))
    return map(filename_to_path,
               filter(not_swagger_dot_json,
                      filter(not_api_doc_file, sorted(filenames))))
1210381
function notFound( req, res, next ) {
        var err = new Error( 'Not Found' );
        err.status = 404;

        next( err );
    }
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();
}
342864
def page_not_found(request, template_name="errors/404.html"):
    
    context = {
        "STATIC_URL": settings.STATIC_URL,
        "request_path": request.path,
    }
    t = get_template(template_name)
    return HttpResponseNotFound(t.render(context, request))
718603
def refresh_swagger(self):
        
        try:
            os.remove(self._get_swagger_filename(self.swagger_url))
        except EnvironmentError as e:
            logger.warn(os.strerror(e.errno))
        else:
            self.__init__()
394085
public void run( String[] args ) throws Exception {

		// Check
		File baseDirectory = null;
		if( args.length != 1
				|| ! (baseDirectory = new File( args[ 0 ])).exists())
			throw new RuntimeException( "The path of the module's directory was expected as an argument." );

		// Validate
		String[] filesToValidate = {
			"target/docs-rest-api/apidocs/ui/swagger.json",
			"target/docs-rest-api/apidocs/ui/swagger-websocket.json"
		};

		for( String path : filesToValidate ) {
			File f = new File( baseDirectory, path );
			if( ! f.exists())
				throw new RuntimeException( path + " was not found." );

			validate( f );
		}
	}