Add Gateway Response configuration to the Swagger file, if necessary
494247
def _add_gateway_responses(self):
        

        if not self.gateway_responses:
            return

        if self.gateway_responses and not self.definition_body:
            raise InvalidResourceException(
                self.logical_id, "GatewayResponses works only with inline Swagger specified in "
                                 "'DefinitionBody' property")

        # Make sure keys in the dict are recognized
        for responses_key, responses_value in self.gateway_responses.items():
            for response_key in responses_value.keys():
                if response_key not in GatewayResponseProperties:
                    raise InvalidResourceException(
                        self.logical_id,
                        "Invalid property '{}' in 'GatewayResponses' property '{}'".format(response_key, responses_key))

        if not SwaggerEditor.is_valid(self.definition_body):
            raise InvalidResourceException(
                self.logical_id, "Unable to add Auth configuration because "
                                 "'DefinitionBody' does not contain a valid Swagger")

        swagger_editor = SwaggerEditor(self.definition_body)

        gateway_responses = {}
        for response_type, response in self.gateway_responses.items():
            gateway_responses[response_type] = ApiGatewayResponse(
                api_logical_id=self.logical_id,
                response_parameters=response.get('ResponseParameters', {}),
                response_templates=response.get('ResponseTemplates', {}),
                status_code=response.get('StatusCode', None)
            )

        if gateway_responses:
            swagger_editor.add_gateway_responses(gateway_responses)

        # Assign the Swagger back to template
        self.definition_body = swagger_editor.swagger
1119549
def add_route(app_or_blueprint, fn, context=default_context):
    
    transmute_func = TransmuteFunction(
        fn,
        args_not_from_request=["request"]
    )
    handler = create_handler(transmute_func, context=context)
    get_swagger_spec(app_or_blueprint).add_func(transmute_func, context)
    for p in transmute_func.paths:
        sanic_path = _convert_to_sanic_path(p)
        app_or_blueprint.add_route(handler, sanic_path, methods=list(transmute_func.methods))
1267658
@Override
    protected void updateHTTPResponseHandlerConfiguration(Map<String,String> configuration)
    {
        //get property part
        String propertyPart=this.getPropertyPart();

        //modify configuration
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.SUBMIT_JSON_OUTPUT_PROPERTY_KEY.toString(),propertyPart),"txn_ref");
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.ERROR_DETECTION_PATH_PROPERTY_KEY.toString(),propertyPart),"status");
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.ERROR_DETECTION_VALUE_PROPERTY_KEY.toString(),propertyPart),"error_");
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.GET_STATUS_JSON_OUTPUT_PROPERTY_KEY.toString(),propertyPart),"fax_status");
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.IN_PROGRESS_STATUS_MAPPING_PROPERTY_KEY.toString(),propertyPart),"ongoing");
        configuration.put(MessageFormat.format(JSONHTTPResponseHandlerConfigurationConstants.ERROR_STATUS_MAPPING_PROPERTY_KEY.toString(),propertyPart),"unanswered;failed;busy");
    }
852254
def create_swagger_json_handler(app, **kwargs):
    

    spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
1271706
function addPathToExpress(handlerObj, handlePath) {
  var self = handlerObj;
  //Check to make sure that the module exists and will load properly to what node expects
  if (moduleExists.call(self, handlePath)) {
    //retrieve the http verbs defined in the handler files and then add to the swagger server
    var handleVerbs = require(handlePath);

    //Get the route path by removing the ./handlers and the .js file extension
    //TODO: Use path names to get these
    var routePath = handlePath.replace(/.*\/handlers/, '');
    routePath = routePath.replace(/\.js/, '');

    swaggerMethods.forEach(function(method) {
      if (handleVerbs[method] && validSwaggerize(self, handleVerbs[method])) {
        self.server[method](routePath, handleVerbs[method]);
      }
    });
  }
}
1271863
def add_swagger_api_route(app, target_route, swagger_json_route):
    
    static_root = get_swagger_static_root()
    swagger_body = generate_swagger_html(
        STATIC_ROOT, swagger_json_route
    ).encode("utf-8")

    async def swagger_ui(request):
        return HTTPResponse(body_bytes=swagger_body, content_type="text/html")

    bp = Blueprint('swagger')
    bp.static(STATIC_ROOT, static_root)

    app.add_route(swagger_ui, target_route, methods=["GET"])
    app.blueprint(bp)
1022814
function addRouteFactory(router, method, end) {
  return (pattern, ...middlewares) => {
    if (typeof pattern === 'function') {
      middlewares = [pattern, ...middlewares];
      pattern = '/';
    }

    // create a route with multiple middlewares
    const route = compose(middlewares, { beforeRunMiddleware: (middleware, req, resp) => {
      const len = req.routePath ? req.routePath.length : 0;
      if (req.url.slice(0, len) !== req.routePath) return false;// url changed
      return true;
    } });
    route.method = method;

    const keys = [];
    const re = ptre(pattern, keys, { end, strict: false, sensitive: false });
    route.re = re;// used to test the remain of req.url
    route.keys = keys;

    router.routes.push(route);

    return router;
  };
}
989172
def create_api_gateway_routes(  self,
                                    lambda_arn,
                                    api_name=None,
                                    api_key_required=False,
                                    authorization_type='NONE',
                                    authorizer=None,
                                    cors_options=None,
                                    description=None,
                                    endpoint_configuration=None
                                ):
        

        restapi = troposphere.apigateway.RestApi('Api')
        restapi.Name = api_name or lambda_arn.split(':')[-1]
        if not description:
            description = 'Created automatically by Zappa.'
        restapi.Description = description
        endpoint_configuration = [] if endpoint_configuration is None else endpoint_configuration
        if self.boto_session.region_name == "us-gov-west-1":
            endpoint_configuration.append("REGIONAL")
        if endpoint_configuration:
            endpoint = troposphere.apigateway.EndpointConfiguration()
            endpoint.Types = list(set(endpoint_configuration))
            restapi.EndpointConfiguration = endpoint
        if self.apigateway_policy:
            restapi.Policy = json.loads(self.apigateway_policy)
        self.cf_template.add_resource(restapi)

        root_id = troposphere.GetAtt(restapi, 'RootResourceId')
        invocation_prefix = "aws" if self.boto_session.region_name != "us-gov-west-1" else "aws-us-gov"
        invocations_uri = 'arn:' + invocation_prefix + ':apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + lambda_arn + '/invocations'

        ##
        # The Resources
        ##
        authorizer_resource = None
        if authorizer:
            authorizer_lambda_arn = authorizer.get('arn', lambda_arn)
            lambda_uri = 'arn:{invocation_prefix}:apigateway:{region_name}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations'.format(
                invocation_prefix=invocation_prefix,
                region_name=self.boto_session.region_name,
                lambda_arn=authorizer_lambda_arn
            )
            authorizer_resource = self.create_authorizer(
                restapi, lambda_uri, authorizer
            )

        self.create_and_setup_methods(  restapi,
                                        root_id,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        0
                                        )

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        root_id,
                                        invocations_uri,
                                        0,
                                        cors_options
                                    )

        resource = troposphere.apigateway.Resource('ResourceAnyPathSlashed')
        self.cf_api_resources.append(resource.title)
        resource.RestApiId = troposphere.Ref(restapi)
        resource.ParentId = root_id
        resource.PathPart = "{proxy+}"
        self.cf_template.add_resource(resource)

        self.create_and_setup_methods(  restapi,
                                        resource,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        1
                                    )  # pragma: no cover

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        resource,
                                        invocations_uri,
                                        1,
                                        cors_options
                                    )  # pragma: no cover
        return restapi
1049479
protected void configureMetrics() {
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS, ESMetrics.class.getName());
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.type", "jest");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.protocol", "${apiman.es.protocol}");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.host", "${apiman.es.host}");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.port", "${apiman.es.port}");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.username", "${apiman.es.username}");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.password", "${apiman.es.password}");
        setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.index", "apiman_metrics");
    }
1315601
function mainEntry(event, context, callback) {
    if ('httpMethod' in event) {
        // http.dispath
        try {
            var gatewayName = event.stageVariables ?
                event.stageVariables.gatewayName :
                http.Gateway.default();
            if (gatewayName === undefined)
                throw new Error("Undefined gateway");
            var gateway = http.allGateways[gatewayName];
            if (gateway === undefined)
                throw new Error("Undefined gateway '" + gatewayName + "'");
            /*
                        gateway.dispatch(event, (response: http.ResponseData) =>
                            done(null, response)
                        );
            */
            gateway.dispatch(event)
                .then(function (v) { return callback(null, v); })
                .catch(function (e) { return callback(null, {
                statusCode: 500,
                headers: {},
                body: "CRITICAL ERROR (level 2)\n\t" + e + "\n" + e.stack
            }); });
        }
        catch (e) {
            callback(null, {
                statusCode: 500,
                headers: {},
                body: "CRITICAL ERROR (level 1)\n\t" + e + "\n" + e.stack
            });
        }
    }
    else
        callback(new Error('unknow event source'), null);
}
8868
@GetMapping(value = "/swagger.yml", produces = "text/yaml")
  public String swagger(Model model, HttpServletResponse response) {
    response.setContentType("text/yaml");
    response.setCharacterEncoding("UTF-8");
    final UriComponents uriComponents =
        ServletUriComponentsBuilder.fromCurrentContextPath().build();
    model.addAttribute("scheme", uriComponents.getScheme());
    String host = uriComponents.getHost();
    if (uriComponents.getPort() >= 0) {
      host += ":" + uriComponents.getPort();
    }
    model.addAttribute("host", host);
    model.addAttribute(
        "entityTypes",
        metaDataService
            .getEntityTypes()
            .filter(e -> !e.isAbstract())
            .map(EntityType::getId)
            .sorted()
            .collect(toList()));
    model.addAttribute("attributeTypes", AttributeType.getOptionsLowercase());
    model.addAttribute("languageCodes", getLanguageCodes().collect(toList()));
    return "view-swagger";
  }
386524
def add_swagger(app, json_route, html_route, **kwargs):
    
    spec = getattr(app, SWAGGER_ATTR_NAME)
    if spec:
        spec = spec.swagger_definition(**kwargs)
    else:
        spec = {}
    encoded_spec = json.dumps(spec).encode("UTF-8")

    @app.route(json_route)
    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={"Access-Control-Allow-Origin": "*"},
            content_type="application/json",
        )

    # add the statics
    static_root = get_swagger_static_root()
    swagger_body = generate_swagger_html(
        STATIC_PATH, json_route
    ).encode("utf-8")

    @app.route(html_route)
    def swagger_ui():
        return Response(swagger_body, content_type="text/html")

    # the blueprint work is the easiest way to integrate a static
    # directory into flask.
    blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,
                          static_folder=static_root)
    app.register_blueprint(blueprint)
840132
def create_swagger_json_handler(app, **kwargs):
    

    spec = get_swagger_spec(app)
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    async def swagger(request):
        return HTTPResponse(
            body_bytes=encoded_spec,
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
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;
}
1345630
function corsHeaders (req, res, next) {
  // Get the default CORS response headers as specified in the Swagger API
  let responseHeaders = getResponseHeaders(req);

  // Set each CORS header
  _.each(accessControl, (header) => {
    if (responseHeaders[header] !== undefined) {
      // Set the header to the default value from the Swagger API
      res.set(header, responseHeaders[header]);
    }
    else {
      // Set the header to a sensible default
      switch (header) {
        case accessControl.allowOrigin:
          // By default, allow the origin host. Fallback to wild-card.
          res.set(header, req.get("Origin") || "*");
          break;

        case accessControl.allowMethods:
          if (req.swagger && req.swagger.path) {
            // Return the allowed methods for this Swagger path
            res.set(header, util.getAllowedMethods(req.swagger.path));
          }
          else {
            // By default, allow all of the requested methods. Fallback to ALL methods.
            res.set(header, req.get("Access-Control-Request-Method") || swaggerMethods.join(", ").toUpperCase());
          }
          break;

        case accessControl.allowHeaders:
          // By default, allow all of the requested headers
          res.set(header, req.get("Access-Control-Request-Headers") || "");
          break;

        case accessControl.allowCredentials:
          // By default, allow credentials
          res.set(header, true);
          break;

        case accessControl.maxAge:
          // By default, access-control expires immediately.
          res.set(header, 0);
          break;
      }
    }
  });

  if (res.get(accessControl.allowOrigin) === "*") {
    // If Access-Control-Allow-Origin is wild-carded, then Access-Control-Allow-Credentials must be false
    res.set("Access-Control-Allow-Credentials", "false");
  }
  else {
    // If Access-Control-Allow-Origin is set (not wild-carded), then "Vary: Origin" must be set
    res.vary("Origin");
  }

  next();
}
228620
def generate_api_gateway():
    """"""
    logger.debug("[#] Setting up the API Gateway")
    client = boto3.client('apigateway', region_name=PRIMARY_REGION)
    matches = [x for x in client.get_rest_apis().get('items', list())
               if x['name'] == API_GATEWAY]
    if len(matches) > 0:
        logger.debug("[#] API Gateway already setup")
        return matches.pop()

    response = client.create_rest_api(
        name=API_GATEWAY,
        description='REST-API to power the Blockade service'
    )
    logger.info("[#] Successfully setup the API Gateway")

    return response