/* Parse requests that request `code` as `response_type`.

@param {http.ServerRequest} req
@api public
772399
function request(req) {
        var clientID = getParam(req, 'client_id')
            , redirectURI = getParam(req, 'redirect_uri')
            , scope = getParam(req, 'scope')
            , state = getParam(req, 'state');

        if (!clientID) {
            throw new AuthorizationError('Missing required parameter: client_id', 'invalid_request');
        }

        if (scope) {
            for (var i = 0, len = separators.length; i < len; i++) {
                var separated = scope.split(separators[i]);
                // only separate on the first matching separator.  this allows for a sort
                // of separator "priority" (ie, favor spaces then fallback to commas)
                if (separated.length > 1) {
                    scope = separated;
                    break;
                }
            }

            if (!Array.isArray(scope)) {
                scope = [scope];
            }
        }

        return {
            clientID: clientID,
            redirectURI: redirectURI,
            scope: scope,
            state: state
        };
    }
86310
async def parse_result(response, response_type=None, *, encoding="utf-8"):
    
    if response_type is None:
        ct = response.headers.get("content-type")
        if ct is None:
            cl = response.headers.get("content-length")
            if cl is None or cl == "0":
                return ""
            raise TypeError(
                "Cannot auto-detect response type "
                "due to missing Content-Type header."
            )
        main_type, sub_type, extras = parse_content_type(ct)
        if sub_type == "json":
            response_type = "json"
        elif sub_type == "x-tar":
            response_type = "tar"
        elif (main_type, sub_type) == ("text", "plain"):
            response_type = "text"
            encoding = extras.get("charset", encoding)
        else:
            raise TypeError("Unrecognized response type: {ct}".format(ct=ct))
    if "tar" == response_type:
        what = await response.read()
        return tarfile.open(mode="r", fileobj=BytesIO(what))
    if "json" == response_type:
        data = await response.json(encoding=encoding)
    elif "text" == response_type:
        data = await response.text(encoding=encoding)
    else:
        data = await response.read()
    return data
1280655
function Router_parseRequest(method, parsedUrl, headers) {
        var all = [];

        this.routes.forEach(function (routeRule) {
            all.push(
                new Promise(function (resolve, reject) {
                    try {
                        resolve(routeRule.parseRequest(method, parsedUrl, headers));
                    } catch (e) {
                        reject(e);
                    }
                })
            );
        });
        return Promise.all(all).then(function (data) {
            var route;
            while (data.length) {
                route = data.shift();
                if (Type.isArray(route) && route.length === 2) {
                    return route;
                }
            }
            return [];
        });
    }
637999
function (req) {
            // increment before assigning to avoid setting request id 0 (which does not work well with abort)
            this.nbRequests++;
            req.id = this.nbRequests;

            var reqMethods = ["GET", "POST", "PUT", "DELETE", "HEAD", "TRACE", "OPTIONS", "CONNECT", "PATCH", "COPY",
                    "PROPFIND", "MKCOL", "PROPPATCH", "MOVE", "LOCK", "UNLOCK", "BIND", "UNBIND", "REBIND"];
            // Assign a request timeout in order of importance:
            // # req.timeout - User specified timeout
            // # req.callback.timeout - Timeout of the callback function (might be set by filters)
            // # this.defaultTimeout - Default IO timeout
            if (req.timeout == null) {
                req.timeout = (req.callback == null || req.callback.timeout == null)
                        ? this.defaultTimeout
                        : req.callback.timeout;
            }

            if (!req.method) {
                req.method = "GET";
            } else {
                req.method = req.method.toUpperCase();
            }

            if (!(require("../utils/Array")).contains(reqMethods, req.method)) {
                return this.$logWarn("The request method %1 is invalid", [req.method]);
            }

            var headers = {};
            // First take the default IO headers
            for (var key in this.headers) {
                if (this.headers.hasOwnProperty(key)) {
                    headers[key] = this.headers[key];
                }
            }
            // Then add POST/PUT-specific headers
            if (req.method === "POST" || req.method === "PUT") {
                for (var key in this.postHeaders) {
                    if (this.postHeaders.hasOwnProperty(key)) {
                        headers[key] = this.postHeaders[key];
                    }
                }
            }
            // Then the headers from the request object
            for (var key in req.headers) {
                if (req.headers.hasOwnProperty(key)) {
                    headers[key] = req.headers[key];
                }
            }

            req.headers = headers;
        }
738995
def parse_response(resp):
        
        if resp.status_code in [200, 201, 202]:
            return resp.json()
        elif resp.status_code == 204:
            return None
        elif resp.status_code == 400:
            raise error.BadRequestError(resp.text)
        elif resp.status_code == 401:
            raise error.UnauthorizedError(resp.text)
        elif resp.status_code == 403:
            raise error.ForbiddenError(resp.text)
        elif resp.status_code == 404:
            raise error.NotFoundError(resp.text)
        elif resp.status_code == 429:
            raise error.TooManyRequestsError(resp.text)
        elif resp.status_code == 503:
            raise error.ServiceUnavailableError(resp.text)
        else:
            raise error.OptimizelyError(resp.text)
1216434
function(response, body) {
        var responseCodes = [
            { codes: 400, message: 'Request was invalid.' },
            { codes: 401, message: 'Bad access token.' },
            { codes: 403, message: 'Bad OAuth scope.' },
            { codes: 404, message: 'Selector did not match any lights.' },
            { codes: 422, message: 'Missing or malformed parameters' },
            { codes: 426, message: 'HTTP was used to make the request instead of HTTPS. Repeat the request using HTTPS instead.' },
            { codes: 429, message: 'The request exceeded a rate limit.' },
            { codes: [ 500, 502, 503, 523 ], message: 'Something went wrong on Lif\'s end.' }
        ];

        var error = '';
        responseCodes.every(function(responseCode) {
            if(_.isArray(responseCode.codes)) {
                responseCode.codes.forEach(function(code) {
                    if (code === response.statusCode) {
                        error = responseCode.message;
                        return false;
                    }

                    return true;
                });
            }
        });

        // Special case HTTP code 422 Unprocessable Entity
        if(response && response.statusCode === 422) {
            error = body.error;
        }

        return error;
    }
9702
function parseurl (req) {
  var url = req.url

  if (url === undefined) {
    // URL is undefined
    return undefined
  }

  var parsed = req._parsedUrl

  if (fresh(url, parsed)) {
    // Return cached URL parse
    return parsed
  }

  // Parse the URL
  parsed = fastparse(url)
  parsed._raw = url

  return (req._parsedUrl = parsed)
}
406750
def _parse_response_types(argspec, attrs):
        
        return_type = argspec.annotations.get("return") or None
        type_description = attrs.parameter_descriptions.get("return", "")
        response_types = attrs.response_types.copy()
        if return_type or len(response_types) == 0:
            response_types[attrs.success_code] = ResponseType(
                type=return_type,
                type_description=type_description,
                description="success",
            )
        return response_types
454713
def parse_response(response)
      case response.content_type
      when JSON_CONTENT_TYPE
        JSON.parse(response.body, quirks_mode: true, symbolize_names: true)
      else
        response.body
      end
    end
529851
function reqrtn(req, res) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.req = req;
    this.res = res;
    this.data = {
    //localHostIpArray:['localhost','127.0.0.1','::1']
    };
    this.isClientInputLoaded = false;
}
581890
function(res) {
    res.setEncoding('utf8');
    var data = "";
    res.on('data', function(chunk) {
      data+=chunk;
    });

    res.on('end', function() {
      // Get HTTP Statuscode and act according to situation
      var code = res.statusCode;
      try { // try to parse JSON
        var answer = JSON.parse(data);
      } catch (e) {
        var err = {};
        err.http_code = 500;
        err.message = "No valid JSON received: "+data;
        callback(err, null);
        return;
      }
      if(code >= 200 && code <= 206) { // request was successful
        callback(null, answer);
      } else if (code >= 300 && code <= 307) { // server send redirect
        // we do not follow anything the server wants us to follow right now, since this should never be the case.
        // instead let's raise an error.
        var err = new Object();
        err.http_code = 500;
        err.message = "Redirects not supported by pastyclient-node"
        callback(err, null);
      } else if (code >= 400 && code <= 418) { // client error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else if(answer.code != undefined && answer.message != undefined) { // New RestError, temporary support both 
          var err = answer;
          err.http_code = code;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Resource not found";
        }
        callback(err, null);
      } else if (code >= 500 && code <= 505) { // server error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Internal Server Error";
        }
        callback(err, null);
      } else {
        // Not existant HTTP code. Raise error.
        var err = new Object();
        err.http_code = 500;
        err.message = "HTTP Status Code "+code+" is not supported by pastyclient-node"
        callback(err, null);
      }
    });
  }
415047
function respondText(res, code, text) {
  res.statusCode = code;
  res.setHeader('Content-Type', 'text/plain');
  return res.end(text.toString());
}
867684
private Map<String, List<Request>> requests(
        final Request req) throws IOException {
        final String header = new RqHeaders.Smart(req).single("Content-Type");
        if (!new EnglishLowerCase(header).string()
            .startsWith("multipart/form-data")) {
            throw new HttpException(
                HttpURLConnection.HTTP_BAD_REQUEST,
                String.format(
                    // @checkstyle LineLength (1 line)
                    "RqMtBase can only parse multipart/form-data, while Content-Type specifies a different type: \"%s\"",
                    header
                )
            );
        }
        final Matcher matcher = RqMtBase.BOUNDARY.matcher(header);
        if (!matcher.matches()) {
            throw new HttpException(
                HttpURLConnection.HTTP_BAD_REQUEST,
                String.format(
                    "boundary is not specified in Content-Type header: \"%s\"",
                    header
                )
            );
        }
        final ReadableByteChannel body = Channels.newChannel(this.stream);
        if (body.read(this.buffer) < 0) {
            throw new HttpException(
                HttpURLConnection.HTTP_BAD_REQUEST,
                "failed to read the request body"
            );
        }
        final byte[] boundary = String.format(
            "%s--%s", RqMtBase.CRLF, matcher.group(1)
        ).getBytes(RqMtBase.ENCODING);
        this.buffer.flip();
        this.buffer.position(boundary.length - 2);
        final Collection<Request> requests = new LinkedList<>();
        while (this.buffer.hasRemaining()) {
            final byte data = this.buffer.get();
            if (data == '-') {
                break;
            }
            this.buffer.position(this.buffer.position() + 1);
            requests.add(this.make(boundary, body));
        }
        return RqMtBase.asMap(requests);
    }
1070825
function getCharset (req) {
  try {
    return contentType.parse(req).parameters.charset.toLowerCase()
  } catch (e) {
    return undefined
  }
}
945628
protected Response request (String req)
        throws IOException
    {
        System.err.println("REQ:" + req);

        // send the request to the server
        _out.println(req);
        _out.flush();

        // now read the response
        String rspstr = _in.readLine();
        // if they closed the connection on us, we should deal
        if (rspstr == null) {
            throw new EOFException();
        }
        System.err.println("RSP:" + rspstr);

        // parse the response
        Response rsp = new Response();
        String codestr = rspstr;

        // assume the response is just a code unless we see a space
        int sidx = rspstr.indexOf(" ");
        if (sidx != -1) {
            codestr = rspstr.substring(0, sidx);
            rsp.message = rspstr.substring(sidx+1);
        }

        try {
            rsp.code = Integer.parseInt(codestr);
        } catch (NumberFormatException nfe) {
            rsp.code = 599;
            rsp.message = "Unparseable response";
        }

        return rsp;
    }
723243
function _request(url, opt) {
      opt = opt || {};
      opt.method = (opt.method || 'GET').toUpperCase();
      opt.headers = opt.headers || {};
      if (matchUrl(url) && matchMethod(opt.method)) {
        const result = extend(true, {}, mockResult);
        const response = {
          status: result.status,
          statusCode: result.status,
          headers: result.headers,
          size: result.responseSize,
          aborted: false,
          rt: 1,
          keepAliveSocket: result.keepAliveSocket || false,
        };

        httpclient.emit('response', {
          error: null,
          ctx: opt.ctx,
          req: {
            url,
            options: opt,
            size: result.requestSize,
          },
          res: response,
        });
        if (opt.dataType === 'json') {
          try {
            result.data = JSON.parse(result.data);
          } catch (err) {
            err.name = 'JSONResponseFormatError';
            throw err;
          }
        } else if (opt.dataType === 'text') {
          result.data = result.data.toString();
        }
        return Promise.resolve(result);
      }
      return rawRequest.call(httpclient, url, opt);
    }
995001
function _ParseTokenResponse(err, body, callback)
	{
		if (err)
		{
			if (callback) callback("Request error: " + err);
			return;
		}

		// try to parse result
		var responseJSON;
		try
		{
			responseJSON = JSON.parse(body);
		}
		catch (JSONerror)
		{
			if (callback) callback("JSON Parse error: " + JSONerror);
			return;
		}

		// check server response for error
		if (responseJSON.error_description)
		{
			if (callback) callback("Server response error " + responseJSON.error_code + ": " + responseJSON.error_description);
			return;
		}

		// check we got an access token
		if (!responseJSON.access_token)
		{
			if (callback) callback("No access token received from PSN OAuth");
			return;
		}

		Log("Got successful OAuth result");

		// store our new tokens
		auth_obj.access_token = 	responseJSON.access_token;
		auth_obj.refresh_token = 	responseJSON.refresh_token;
		// calculate expire time of these tokens (shave off half a minute)
		auth_obj.expire_time =		(new Date().getTime()) + ((responseJSON.expires_in - 30) * 1000);

		// save the data object
		DoSave(function()
			{
				// return no error
				if (callback) callback(false);
			}
		);
	}