Modularized because API was broken.

        Need to be able to inject Mocked response objects here.
165421
def _do_request(self, method, *args, **kwargs):
        
        log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
            args[0], kwargs.get('headers'), kwargs.get('json'), method,),
            level=logging.DEBUG,)
        requests_method = getattr(requests, method)
        return self._handle_response(requests_method(*args, **kwargs))
423600
def hook_response(self, response):
        " "
        # Decode content with json.
        response._content = json.loads(response.content)
        return response
1242878
private static Response createResponse(Object object, AlluxioConfiguration alluxioConf,
      @Nullable Map<String, Object> headers) {
    if (object instanceof Void) {
      return Response.ok().build();
    }
    if (object instanceof String) {
      // Need to explicitly encode the string as JSON because Jackson will not do it automatically.
      ObjectMapper mapper = new ObjectMapper();
      try {
        return Response.ok(mapper.writeValueAsString(object)).build();
      } catch (JsonProcessingException e) {
        return createErrorResponse(e, alluxioConf);
      }
    }

    Response.ResponseBuilder rb = Response.ok(object);
    if (headers != null) {
      headers.forEach(rb::header);
    }

    if (alluxioConf.getBoolean(PropertyKey.WEBUI_CORS_ENABLED)) {
      return makeCORS(rb).build();
    }

    return rb.build();
  }
503101
function loadMockHttpRequestError (mockData, options) {
    immutableAutomock.httpRequestErrorMocks[mockData.data.httpRequestId] = mockData.data
}
842800
function mockResponseBody (req, res, next) {
  if (res.swagger) {
    if (res.swagger.isEmpty) {
      // There is no response schema, so send an empty response
      util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path);
      res.send();
    }
    else {
      // Serialize the response body according to the response schema
      let schema = new JsonSchema(res.swagger.schema);
      let serialized = schema.serialize(res.swagger.wrap(res.body));

      switch (res.swagger.schema.type) {
        case "object":
        case "array":
        case undefined:
          sendObject(req, res, next, serialized);
          break;

        case "file":
          sendFile(req, res, next, serialized);
          break;

        default:
          sendText(req, res, next, serialized);
      }
    }
  }
  else {
    next();
  }
}
250114
def post_mockdata_url(service_name, implementation_name,
                      url, headers, body,
                      dir_base=dirname(__file__)):
    
    # Currently this post method does not return a response body
    response = MockHTTP()
    if body is not None:
        if "dispatch" in url:
            response.status = 200
        else:
            response.status = 201
        response.headers = {"X-Data-Source": service_name + " file mock data",
                            "Content-Type": headers['Content-Type']}
    else:
        response.status = 400
        response.data = "Bad Request: no POST body"
    return response
680759
function registerMock(post) {

        var responseObj = {};
        responseObj["statusCode"] = parseInt(post.statusCode) || 200;
        responseObj["header"] = post.header || {
                'Content-Type': post.contentType || 'application/json',
                'Access-Control-Allow-Origin': '*'
            };
        responseObj["contentType"] = post.contentType || "application/json";
        if (typeof post.responseText == 'object') {

            responseObj["responseText"] = JSON.stringify(post.responseText);

        } else {
            responseObj["responseText"] = post.responseText || "This is a fake response";
        }


        responseObj["responseFile"] = post.responseFile;

        responseObj["id"] = post.id;
        responseObj["keyValues"] = post.keyValues || {};
        responseObj["eval"] = post.eval;
        responseObj["delayTime"] = parseInt(post.delayTime) || 0;

        var requestPath = post.requestPath;
        if (post.requestJSONBody == '' || post.requestJSONBody == null) {

            mockReqRespMap[requestPath] = responseObj;

        } else {
            responseObj["requestJSONBody"] = post.requestJSONBody;
            var uniqueID = md5(JSON.stringify(post.requestJSONBody));
            mockReqRespMap[requestPath + uniqueID] = responseObj;
        }
    }
184648
function (params) {
    var resourceObject = {
      url: resource.url(),
      method: method,
      headers: resource.headers
    };
    
    if (typeof params === 'object') {
      resourceObject.json = true;
      resourceObject.body = params;
    }
    else if (typeof params === 'string') {
      resourceObject.body = params;
    }
    
    // Should this resource be mocked, or real?
    // It is ensured that you can define the mock before
    // or after the resource is defined
    var mock = self.mock(method, uri);
    if (mock) {
      mock.request = {
        body: params,
        method: method,
        pathname: slash(uri),
        headers: resource.headers
      };
      return mock.fn()();
    }
    else {
      return rawHttp(extend(resourceObject, resource.xhrOptions || {}));
    }
  }
141608
public Observable<ServiceResponse<LuisApp>> exportWithServiceResponseAsync(UUID appId, String versionId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        if (versionId == null) {
            throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.export(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LuisApp>>>() {
                @Override
                public Observable<ServiceResponse<LuisApp>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LuisApp> clientResponse = exportDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }
458646
function MockRes (url, cb) {
    this.url = url;
    this.headers = {};
    this.content = undefined;
    this.setHeader = function (name, value) {
        this.headers[name] = value;
    }.bind(this);
    this.end = function (content) {
        this.content = content;
        cb(this);
    }.bind(this);
}
1302261
def decorate(self, app):
		
		from functools import wraps

		@wraps(app)
		def decorated(environ, start_response):
			# capture any start_response from the app
			app_response = {}
			app_response['status'] = "200 OK"
			app_response['headers'] = []
			app_response['written'] = BytesIO()
			def custom_start_response(status, headers, *args, **kwargs):
				app_response['status'] = status
				app_response['headers'] = headers
				app_response['args'] = args
				app_response['kwargs'] = kwargs
				return app_response['written'].write
			returned = app(environ, custom_start_response)

			# callbacks from the serialization
			def set_http_code(status):
				app_response['status'] = str(status)
			def set_header(header, value):
				app_response['headers'] = [(h,v) for (h,v) in app_response['headers'] if h.lower() != header.lower()]
				app_response['headers'].append((header, value))
			def set_content_type(content_type):
				set_header('Content-Type', content_type)

			# do the serialization
			accept = environ.get('HTTP_ACCEPT', '')
			new_return = self.output(returned, accept, set_http_code, set_content_type)

			# set the Vary header
			vary_headers = (v for (h,v) in app_response['headers'] if h.lower() == 'vary')
			vary_elements = list(itertools.chain(*[v.split(',') for v in vary_headers]))
			vary_elements = list(set([v.strip() for v in vary_elements]))
			if '*' not in vary_elements and 'accept' not in (v.lower() for v in vary_elements):
				vary_elements.append('Accept')
				set_header('Vary', ', '.join(vary_elements))

			# pass on the result to the parent WSGI server
			parent_writer = start_response(app_response['status'],
			                               app_response['headers'],
			                               *app_response.get('args', []),
			                               **app_response.get('kwargs', {}))
			written = app_response['written'].getvalue()
			if len(written) > 0:
				parent_writer(written)
			return new_return
		return decorated
1235479
function callApi(endpoint, schema) {
  const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint;

  return fetch(fullUrl)
    .then(response =>
      response.json().then(json => ({ json, response }))
    ).then(({ json, response }) => {
      if (json.error) {
        throw new Error(json.error);
      }
      if (!response.ok) {
        throw new Error(json && json.message || response.statusText || response.status + ' http error');
      }

      const camelizedJson = camelizeKeys(json);
      const nextPageUrl = getNextPageUrl(response);

      return Object.assign({},
        normalize(camelizedJson, schema),
        { nextPageUrl }
      );
    })
    .then(
      response => ({response})
    );
}
897685
function executeApi(apiName, opts, extras){

  var emitter = new Emitter()
    , apiItem
    , token = opts.access_token
    , form, method, path
    , url
    ;
  
  if(/^(https?:\/\/|\/)/.test(apiName)){
    if(apiName.indexOf('/') === 0){
      url = api.HOST + apiName;
    }else{
      url = apiName;
    }
    extras = extras || {};
    method = extras.method;
    
  }else{
    apiItem = getApiItem(apiName);
    if(!apiItem){
      process.nextTick(function(){
        emitter.emit('error', 'no or not support api: ' + apiName);
      });
      return emitter;
    }
    
    path = apiItem.path;
    method = apiItem.method;
    
    url = api.HOST + api.PREPATH + path + '.json';
  }
  
  if(method == 'post'){
    form = opts;
    opts = {};
  }
  
  delete opts.access_token;
  
  request({
      url: url + '?access_token=' + token
    , method: method
    , qs: opts
    , form: form
  }, function(err, res, reply){
    if(err){
      emitter.emit('error', err);
    }else{
      try{
        reply = JSON.parse(reply);
        emitter.emit('success', reply);
      }catch(e){
        emitter.emit('error', reply);
      }
    }
  });
  
  return emitter;
}
1209570
function createMiddleware(router, validator) {
  /**
   * Checks request and response against a swagger spec
   * Uses the usual koa context attributes
   * Uses the koa-bodyparser context attribute
   * Sets a new context attribute: {object} parameter
   */
  return function* middleware(next) {
    // Routing matches
    try {
      var routeMatch = match.path(router, this.path);
    } catch(e) {
      // TODO: let an option before doing that, strict mode throws the error
      yield next;
      return false;
    }
    this.pathParam = routeMatch.param; // Add the path's params to the context
    var methodDef = match.method(routeMatch.def, this.method);


    // Parameters check & assign
    this.parameter = check.parameters(validator,
      methodDef.parameters || [], this);

    // Let the implementation happen
    yield next;

    // Response check
    var statusDef = match.status(methodDef.responses || {}, this.status);
    check.sentHeaders(validator, statusDef.headers || {}, this.sentHeaders);
    if(statusDef.schema) {
      check.body(validator, statusDef.schema, yield this.body);
    }
  };
}
483435
def _api_response(response):
    '''
    
    '''
    if response.status_code == 404:
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError('Element doesn\'t exists')
    if response.status_code == 401:
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError('Bad username or password')
    elif response.status_code == 200 or response.status_code == 500:
        try:
            data = salt.utils.json.loads(response.content)
            if data['exit_code'] != 'SUCCESS':
                __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
                raise CommandExecutionError(data['message'])
            return data
        except ValueError:
            __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
            raise CommandExecutionError('The server returned no data')
    else:
        response.raise_for_status()
9572
function (url) {
        return new Promise(function (resolve, reject) {
            middleware(new MockReq(url), new MockRes(url, resolve), reject);
        });
    }
1075171
private ApiResponse buildResponseFromContext(Context c) {
		Map<String, String> fields = new HashMap<>();
		fields.put("name", c.getName());
		fields.put("id", Integer.toString(c.getIndex()));
		fields.put("description", c.getDescription());
		fields.put("inScope", Boolean.toString(c.isInScope()));
		fields.put("excludeRegexs", jsonEncodeList(c.getExcludeFromContextRegexs()));
		fields.put("includeRegexs", jsonEncodeList(c.getIncludeInContextRegexs()));
		
		AuthenticationMethod authenticationMethod = c.getAuthenticationMethod();
		if(authenticationMethod != null){
			Pattern pattern = authenticationMethod.getLoggedInIndicatorPattern();
			fields.put("loggedInPattern",  pattern == null ? "" : pattern.toString());
			pattern = authenticationMethod.getLoggedOutIndicatorPattern();
			fields.put("loggedOutPattern", pattern == null ? "" : pattern.toString());
			AuthenticationMethodType type = authenticationMethod.getType();
			fields.put("authType", type == null ? "" : type.getName());
		}
		
		AuthorizationDetectionMethod authorizationDetectionMethod = c.getAuthorizationDetectionMethod();
		if(authorizationDetectionMethod != null){
			fields.put("authenticationDetectionMethodId",String.valueOf(authorizationDetectionMethod.getMethodUniqueIdentifier()));
		}
		
		fields.put("urlParameterParserClass", c.getUrlParamParser().getClass().getCanonicalName());
		fields.put("urlParameterParserConfig", c.getUrlParamParser().getConfig());
		fields.put("postParameterParserClass", c.getPostParamParser().getClass().getCanonicalName());
		fields.put("postParameterParserConfig", c.getPostParamParser().getConfig());
		
		return new ApiResponseSet<String>("context", fields);
	}