Serves the Swagger description of the REST API. As host, fills in the host where the controller
lives. As options for the entity names, contains only those entity names that the user can
actually see.
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";
  }
973059
def create(entity)
      url = "#{DEFAULT_HOST}/#{entity.path}"
      uri = URI(url)
      response = http_response(:post, uri, body: entity.to_hash)
      entity.attributes = JSON.parse(response.body)
      entity
    end
1108591
private void serve(HttpRequest request, HttpResponse response) {
		String url = request.getUri();
		System.out.println("[Server] serve " + url);
		IncomingWebRequestTracer incomingWebrequestTracer = oneAgentSDK.traceIncomingWebRequest(webAppInfo, url, request.getMethod());

		// add request header, parameter and remote address before start:
		for (Entry<String, List<String>> headerField : request.getHeaders().entrySet()) {
			for (String value : headerField.getValue()) {
				incomingWebrequestTracer.addRequestHeader(headerField.getKey(), value);
			}
		}
		for (Entry<String, List<String>> parameter : request.getParameters().entrySet()) {
			for (String value : parameter.getValue()) {
				incomingWebrequestTracer.addParameter(parameter.getKey(), value);
			}
		}
		incomingWebrequestTracer.setRemoteAddress(request.getRemoteIpAddress());

		incomingWebrequestTracer.start();
		try {
			response.setContent("Hello world!".getBytes());
			response.setStatusCode(200);
			incomingWebrequestTracer.setStatusCode(200);
		} catch (Exception e) {
			// we assume, container is sending http 500 in case of exception is thrown while serving an request:
			incomingWebrequestTracer.error(e);
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			incomingWebrequestTracer.end();
		}
	}
663231
function serveSettings(request, response) {
    var referrer_url,
        debug = false;

    // Check the referrer for a debug option
    if (request.headers.referer) {
        referrer_url = url.parse(request.headers.referer, true);
        if (referrer_url.query && referrer_url.query.debug) {
            debug = true;
        }
    }

    SettingsGenerator.get(debug, function(err, settings) {
        if (err) {
            winston.error('Error generating settings', err);
            response.writeHead(500, 'Internal Server Error');
            return response.end();
        }

        if (request.headers['if-none-match'] && request.headers['if-none-match'] === settings.hash) {
            response.writeHead(304, 'Not Modified');
            return response.end();
        }

        response.writeHead(200, {
            'ETag': settings.hash,
            'Content-Type': 'application/json'
        });
        response.end(settings.settings);
    });
}
847493
private void taskHostStatus(RESTRequest request, RESTResponse response) {
        String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID);
        String host = RESTHelper.getRequiredParam(request, APIConstants.PARAM_HOST);

        String taskHostStatusJson = getMultipleRoutingHelper().getHostDetails(taskID, host);
        OutputHelper.writeJsonOutput(response, taskHostStatusJson);
    }
138652
def detail(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="Get specified resource.",
           middleware=None):
    # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation
    
    def inner(c):
        op = Operation(c, path or PathParam('{key_field}'), method, resource, tags, summary, middleware)
        op.responses.add(Response(HTTPStatus.OK, "Get a {name}"))
        op.responses.add(Response(HTTPStatus.NOT_FOUND, "Not found", Error))
        return op
    return inner(callback) if callback else inner
1358659
def add_swagger(app, json_route, html_route):
    
    app.add_route(create_swagger_json_handler(app), json_route, methods=["GET"])
    add_swagger_api_route(app, html_route, json_route)
777894
function serve(req, res) {
  var responseIsArray = Array.isArray(res.entityResponse);
  util.invariant(responseIsArray, 'Response values are required.');

  res.json({ values: res.entityResponse });
}
1132121
def load_swagger_json(swagger_json, ptr_str="$ref"):
        
        refs = []

        def store_refs(d):
            if len(d) == 1 and ptr_str in d:
                refs.append(d)
            return d

        swagger_content = json.load(swagger_json, object_hook=store_refs)
        for ref in refs:
            _, target = ref.popitem()
            assert target[0] == "#"
            ref.update(resolve_pointer(swagger_content, target[1:]))
        return swagger_content
560167
@Override
    public String getDescription() {
        String hostDescr = host;
        try {
            if (hostDescr == null) {
                hostDescr = NetworkUtil.getLocalAddress().getHostName();
            }
        } catch (IOException e) {
            hostDescr = "localhost";
        }
        return "Jolokia Agent: http://" + hostDescr + ":" + getPort() + "/jolokia";
    }
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
392023
def _to_swagger(base=None, description=None, resource=None, options=None):
    # type: (Dict[str, str], str, Resource, Dict[str, str]) -> Dict[str, str]
    
    definition = dict_filter(base or {}, options or {})

    if description:
        definition['description'] = description.format(
            name=getmeta(resource).name if resource else "UNKNOWN"
        )

    if resource:
        definition['schema'] = {
            '$ref': '#/definitions/{}'.format(getmeta(resource).resource_name)
        }

    return definition
527160
def serve_doc(app, url):
    
    @app.route(url, doc=False)
    def index(env, req):
        ret = ''
        for d in env['doc']:
            ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d)
        return ret
965654
def get_host(self, host):
        '''  '''

        if len(self.index) == 0:
            # Need to load index from cache
            self.load_index_from_cache()

        if not host in self.index:
            # try updating the cache
            self.do_api_calls_update_cache()
            if not host in self.index:
                # host might not exist anymore
                return {}

        (region, instance_id) = self.index[host]

        instance = self.get_instance(region, instance_id)
        return self.get_host_info_dict_from_instance(instance)
529672
def serve_home(self, environ):
        
        home_view = BaseInsertView(self.rewriterapp.jinja_env, 'index.html')
        fixed_routes = self.warcserver.list_fixed_routes()
        dynamic_routes = self.warcserver.list_dynamic_routes()

        routes = fixed_routes + dynamic_routes

        all_metadata = self.metadata_cache.get_all(dynamic_routes)

        content = home_view.render_to_string(environ,
                                             routes=routes,
                                             all_metadata=all_metadata)

        return WbResponse.text_response(content, content_type='text/html; charset="utf-8"')
789422
private function buildShowAction() {
        $api = new Swagger\Api();
        $api->setPath('/' . $this->getClassName() . '/{id}');
        $operation = new Swagger\Operation();
        $operation->setMethod('GET');
        $operation->setSummary('Find ' . ucfirst($this->getModel()->getSource()) . ' by id.');
        $operation->setNotes('Returns ' . $this->singularModelA_Or_An() . ' based on ID.');

        $responseMessage = new Swagger\ResponseMessage();
        $responseMessage->setCode(200);
        $responseMessage->setMessage(ucfirst($this->getModel()->getSource()));
        $responseMessage->setResponseModel($this->getClassName());
        $operation->addResponseMessage($responseMessage);

        $responseMessage = $this->invalidFieldSpecifiedError();
        $operation->addResponseMessage($responseMessage);

        $responseMessage = $this->notAuthorizedResponse();
        $operation->addResponseMessage($responseMessage);

        $responseMessage = $this->notFoundResponse();
        $operation->addResponseMessage($responseMessage);

        $operation->addParameter($this->buildIdParameter());
        $operation->addParameter($this->buildFieldsParameter());
        $api->addOperation($operation);

        $method = new Object\Method();
        $method->setDescription($api->__toString());
        $method->setReturnType('void');
        $method->setAccess('public');
        $method->setName('showAction');
        $method->setContent('parent::showAction();');
        $this->getObject()->addMethod($method);
    }
370044
private function setHostFromUri()
    {
        $this->hostFromUri = true;

        $host = $this->uri->getHost();

        if (!empty($host)) { // Do not set Host header if URI has no host.
            $port = $this->uri->getPort();
            if (null !== $port) {
                $host = sprintf('%s:%d', $host, $port);
            }

            parent::setHeader('Host', $host);
        }
    }