Convert an node response to a standard sdk response object

@param {Object} request {url, method, headers, retries}
@param {http.IncomingMessage} response
@param {String} body
@return {Object} response
10791
function createResponse(request, response, body){
  return {
    statusCode: response.statusCode,
    statusText: response.statusMessage,
    headers: response.headers,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: body,
    retries: 0,
    throttled: false
  };
}
588040
function parseMwsResponse(method, headers, response, callback) {
  // if it's XML, then we an parse correctly
  if (headers && headers['content-type'] == 'text/xml') {
    xml2js.parseString(response, {explicitArray: false}, function(err, result) {
      if (err) {
        return callback(err);
      }

      if (result.ErrorResponse) {
        err = {
          Code: 'Unknown',
          Message: 'Unknown MWS error'
        };

        if (result.ErrorResponse.Error) {
          err = result.ErrorResponse.Error;
        }

        return callback(error.apiError(err.Code, err.Message, result));
      } else {
        callback(null, new Response(method, result));
      }
    });
  } else {
    callback(null, new Response(method, { "Response": response }));
  }
}
1366460
function respond(ctx) {
  // allow bypassing koa
  if (false === ctx.respond) return;

  const res = ctx.res;
  if (!ctx.writable) return;

  let body = ctx.body;
  const code = ctx.status;

  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    ctx.body = null;
    return res.end();
  }

  if ("HEAD" == ctx.method) {
    if (!res.headersSent && isJSON(body)) {
      ctx.length = Buffer.byteLength(JSON.stringify(body));
    }
    return res.end();
  }

  // status body
  if (null == body) {
    body = ctx.message || String(code);
    if (!res.headersSent) {
      ctx.type = "text";
      ctx.length = Buffer.byteLength(body);
    }
    return res.end(body);
  }

  // responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ("string" == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

  // body: json
  body = JSON.stringify(body);
  if (!res.headersSent) {
    ctx.length = Buffer.byteLength(body);
  }
  res.end(body);
}
49409
public static SimpleResponse makeResponse(SimpleRequest request) {
    if (request.getResponseSize() > 0) {
      if (!Messages.PayloadType.COMPRESSABLE.equals(request.getResponseType())) {
        throw Status.INTERNAL.augmentDescription("Error creating payload.").asRuntimeException();
      }

      ByteString body = ByteString.copyFrom(new byte[request.getResponseSize()]);
      Messages.PayloadType type = request.getResponseType();

      Payload payload = Payload.newBuilder().setType(type).setBody(body).build();
      return SimpleResponse.newBuilder().setPayload(payload).build();
    }
    return SimpleResponse.getDefaultInstance();
  }
489827
function request(url, options, callback)
{
  var connection;

  if (typeof options == 'function')
  {
    callback = options;
    options  = {};
  }

  connection = hyperquest(url, options, once(function(error, response)
  {
    if (error)
    {
      callback(error, response);
      return;
    }

    // set body
    response.body = '';

    // accumulate response body
    response.on('data', function(data)
    {
      response.body += data.toString();
    });

    response.on('end', function()
    {
      callback(null, response);
    });
  }));

  return connection;
}
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;
    }
466591
function (request, response) {
    var path = url.parse(request.url, false).pathname;

    if (path === '/') {
      // A base request just prints out the current Imagine version
      response.writeHead(200, { 'content-type': 'application/json' });
      response.end(JSON.stringify({ version: '0.1.0' }));
    } else {
      // All other requests are passed to the handler
      new RequestHandler(request, response).handle();
    }
  }
253081
function respond () {
  let res = this.res
  let body = this.body
  let code = this.status

  if (this.respond === false) return endContext(this)
  if (res.headersSent || this._finished != null) return

  this.set('server', 'Toa/' + Toa.VERSION)
  if (this.config.poweredBy) this.set('x-powered-by', this.config.poweredBy)
  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    this.body = null
    res.end()
  } else if (this.method === 'HEAD') {
    if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body))
    res.end()
  } else if (body == null) {
    // status body
    this.type = 'text'
    body = this.message || String(code)
    this.length = Buffer.byteLength(body)
    res.end(body)
  } else if (typeof body === 'string' || Buffer.isBuffer(body)) {
    res.end(body)
  } else if (body instanceof Stream) {
    body.pipe(res)
    // to ensure `res.headersSent === true` before `context.emit("end")`
    // if "error" occured before "data", it will goto `onResError(this, error)`
    body.once('data', () => endContext(this))
    return
  } else {
    // body: json
    body = JSON.stringify(body)
    this.length = Buffer.byteLength(body)
    res.end(body)
  }
  endContext(this)
}
1219232
function onResponse( response ) {
		res = response;
		if ( res.statusCode !== 200 ) {
			err = {
				'status': res.statusCode,
				'message': ''
			};
		}
		debug( 'Received a response from query endpoint.' );
		debug( 'Response status: %s.', res.statusCode );

		debug( 'Response headers: %s', JSON.stringify( res.headers ) );

		res.setEncoding( 'utf8' );
		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}
446146
function parse(method, req, res, options) {
    return new Promise(function(resolve, reject) {
        BodyParser[method](options)(req, res, function(err) {
            if (err) {
                return reject(err);
            }

            return resolve();
        });
    });
}
976904
def to_response response, headers
        body = ""
        response.each do |s|
          body << s.to_s
        end
        ["[#{body},#{headers.to_json.to_s}]"]
      end
1219459
function _request (client, url, body, method, callback, times = 1) {
  if (client.isDebug) {
    debug('Push URL :' + url)
    if (body) {
      debug('Body :' + body)
    }
    // debug("Auth :" + JSON.stringify(auth))
    debug('Method :' + method)
    debug('Times/MaxTryTimes : ' + times + '/' + client.maxTryTimes)
  }

  var _callback = function (err, res, body) {
    if (err) {
      if (err.code === 'ETIMEDOUT' && err.syscall !== 'connect') {
        // response timeout
        return callback(new JError.APIConnectionError(
          'Response timeout. Your request to the server may have already received, please check whether or not to push',
          true))
      } else if (err.code === 'ENOTFOUND') {
        // unknown host
        return callback(new JError.APIConnectionError('Known host : ' + url))
      }
      // other connection error
      if (times < client.maxTryTimes) {
        return _request(client, url, body, method, callback, times + 1)
      } else {
        return callback(new JError.APIConnectionError('Connect timeout. Please retry later.'))
      }
    }
    if (res.statusCode === 200) {
      if (body.length !== 0) {
        if (client.isDebug) {
          debug('Success, response : ' + body)
        }

        try {
          callback(null, JSON.parse(body))
        } catch (e) {
          callback(e)
        }
      } else {
        if (client.isDebug) {
          debug('Success, response : ' + body)
        }
        callback(null, 200)
      }
    } else {
      if (client.isDebug) {
        debug('Fail, HttpStatusCode: ' + res.statusCode + ' result: ' + body.toString())
      }
      callback(new JError.APIRequestError(res.statusCode, body))
    }
  }

  Request[method.toLowerCase()]({
    url: url,
    body: body,
    auth: {
      user: client.appkey,
      pass: client.masterSecret
    },
    timeout: client.readTimeOut,
    proxy: client.proxy
  }, _callback)
}
216878
function httpResponse (response) {
  if (!response) {
    throw new Error('Unable to parse response.')
  }
  const errorAttrs = response.Chyba && response.Chyba.attributes
  if (errorAttrs) {
    throw new Error(`${response.Chyba.$value} (${errorAttrs.kod})`)
  }
  const body = response.Potvrzeni && response.Potvrzeni.attributes
  const header = response.Hlavicka && response.Hlavicka.attributes
  if (!body || !header) {
    throw new Error('Unable to read response.')
  }
}
608642
function createResponse(xhr, request){
  
  // XHR header processing borrowed from jQuery
  var responseHeaders = {}, match;
  while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
		responseHeaders[match[1].toLowerCase()] = match[2];
	}
	
  return {
    statusCode: xhr.status,
    statusText: xhr.statusText,
    headers: responseHeaders,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: xhr.responseText,
    retries: 0,
    throttled: false
  };
}
700888
function(req, res, next) {
    // If we timed out before managing to respond, don't send the response
    if (res.headersSent) {
      return;
    }

    // Look for `.json` or `.xml` extension in path
    // And override request accept header
    if (/.json$/.test(req.path)) {
      req.headers.accept = 'application/json';
    } else if (/.xml$/.test(req.path)) {
      req.headers.accept = 'application/xml';
    }

    // Use request accept header to determine response content-type
    res.format({
      json: function() {
        res.status(res.code).jsonp(res.data);
      },
      xml: function() {
        var xml;
        try {
          var xmlData = JSON.parse(JSON.stringify(res.data));
          xml = this.xmlBuilder.buildObject(xmlData);
          res.set('Content-Type', 'application/xml; charset=utf-8');
          res.status(res.code).send(xml);
        } catch (e) {
          res.status(500).end();
        }
      }.bind(this)
    });
  }
1258106
function (endPoint, request, response) {
                var self = this,
                    context,
                    requestHandler,
                    handledWithErrorHandler = false,
                    buffers = [],
                    bufferLength = 0;

                // create a new application domain for the request
                var domain = Domain.create();

                domain.add(request);
                domain.add(response);

                // request.setEncoding('utf8');

                request.on('data', function (chunk) {
                    buffers.push(chunk);
                    bufferLength += chunk.length;
                });

                response.on('close', function () {
                    domain.dispose();
                });

                domain.on('error', handleError);


                request.on('end', function () {

                    request.body = new Buffer(bufferLength);

                    var pos = 0;

                    for (var i = 0; i < buffers.length; i++) {
                        buffers[i].copy(request.body, pos);
                        pos += buffers[i].length;
                    }

                    request.body.content = request.body.toString();

                    buffers = null;

                    domain.run(function () {
                        // create the new context object
                        context = new Context(self, endPoint, request, response);

                        // and set the chosen handler
                        requestHandler = self.$handlers.getRequestHandler(context);
                        context.handler = requestHandler;

                        flow()
                            .seq(function (cb) {
                                context._executeHook("beginRequest", cb);
                            })
                            .seq(function (cb) {
                                if (requestHandler.$.autoStartSession) {
                                    context.session.start(cb);
                                } else {
                                    cb();
                                }
                            })
                            .seq(function (cb) {
                                requestHandler.handleRequest(context, cb);
                            })
                            .exec(function (err) {
                                if (err) {
                                    handleError(err);
                                } else {
                                    context.response.end();
                                }
                            });
                    });
                });

                function handleError(err) {

                    if (!handledWithErrorHandler) {
                        handledWithErrorHandler = true;

                        var exceptionHandler = new ExceptionHandler(err);
                        try {
                            exceptionHandler.handleRequest(context, function (err) {
                                err && handleErrorTheHardWay(err);
                            });
                        } catch (e) {
                            handleErrorTheHardWay(err);
                        }

                    } else {
                        // error handler didn't do the job well
                        handleErrorTheHardWay(err);
                    }
                }

                function handleErrorTheHardWay(error) {

                    console.error(error);

                    try {
                        response.writeHead(500);
                    } catch (error) {
                        console.error('Error sending 500', error, request.url);
                    }

                    response.end('Internal Server Error');
                    domain.dispose();
                }

            }
233137
function parseResponse(body) {
  var pgt = '';
  var result = body.match(/action="([\s\S]*?)"/);
  if (result) {
    result = result[1];

    var uri = url.parse(result, true);
    var pathname = uri.pathname;

    pgt = pathname.substr(pathname.lastIndexOf('/') + 1);
  }

  return pgt;
}