Sends an HTTP reply to the client.
@param status The status of the request (e.g. 200 OK or 404 Not Found).
@param buf The content of the reply to send.
556324
public void sendBuffer(final HttpResponseStatus status,
                          final ChannelBuffer buf,
                          final String contentType) {
    if (!chan.isConnected()) {
      if(stats != null) {
        stats.markSendFailed();
      }
      done();
      return;
    }
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);

    // TODO(tsuna): Server, X-Backend, etc. headers.
    // only reset the status if we have the default status, otherwise the user
    // already set it
    response.setStatus(status);
    response.setContent(buf);
    final boolean keepalive = HttpHeaders.isKeepAlive(request);
    if (keepalive) {
      HttpHeaders.setContentLength(response, buf.readableBytes());
    }
    final ChannelFuture future = chan.write(response);
    if (stats != null) {
      future.addListener(new SendSuccess());
    }
    if (!keepalive) {
      future.addListener(ChannelFutureListener.CLOSE);
    }
    done();
  }
1342018
public void send(byte[] buf) {
        if (log.isTraceEnabled()) {
            log.trace("send binary: {}", Arrays.toString(buf));
        }
        // send the incoming bytes
        send(Packet.build(buf));
    }
1329853
public void sendStatus(Status status) {
        if (connection != null) {
            final boolean andReturn = !status.getCode().equals(StatusCodes.NS_DATA_START);
            final Invoke event = new Invoke();
            if (andReturn) {
                final PendingCall call = new PendingCall(null, CALL_ON_STATUS, new Object[] { status });
                if (status.getCode().equals(StatusCodes.NS_PLAY_START)) {
                    IScope scope = connection.getScope();
                    if (scope.getContext().getApplicationContext().containsBean(IRtmpSampleAccess.BEAN_NAME)) {
                        IRtmpSampleAccess sampleAccess = (IRtmpSampleAccess) scope.getContext().getApplicationContext().getBean(IRtmpSampleAccess.BEAN_NAME);
                        boolean videoAccess = sampleAccess.isVideoAllowed(scope);
                        boolean audioAccess = sampleAccess.isAudioAllowed(scope);
                        if (videoAccess || audioAccess) {
                            final Call call2 = new Call(null, "|RtmpSampleAccess", null);
                            Notify notify = new Notify();
                            notify.setCall(call2);
                            notify.setData(IoBuffer.wrap(new byte[] { 0x01, (byte) (audioAccess ? 0x01 : 0x00), 0x01, (byte) (videoAccess ? 0x01 : 0x00) }));
                            write(notify, connection.getStreamIdForChannelId(id));
                        }
                    }
                }
                event.setCall(call);
            } else {
                final Call call = new Call(null, CALL_ON_STATUS, new Object[] { status });
                event.setCall(call);
            }
            // send directly to the corresponding stream as for some status codes, no stream has been created  and thus "getStreamByChannelId" will fail
            write(event, connection.getStreamIdForChannelId(id));
        }
    }
94739
public void sendError(int status, String message)
        throws IOException
    {
        // Find  error page.
        String error_page =
            _servletHttpRequest.getServletHandler().getErrorPage(status,_servletHttpRequest);

        resetBuffer();
        
        // Handle error page?
        if (error_page==null)
        {
            // handle normally
            _httpResponse.sendError(status,message);
        }
        else
        {   
            _httpResponse.setStatus(status,message);
            
            if (message == null)
            {
                message= (String)HttpResponse.__statusMsg.get(TypeUtil.newInteger(status));
                if (message == null)
                    message= "" + status;
            }

            // handle error page
            ServletHolder holder = _servletHttpRequest.getServletHolder();
            if (holder!=null)
                _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_SERVLET_NAME,
                                                 holder.getName());
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_REQUEST_URI,
                                             _servletHttpRequest.getRequestURI());
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_STATUS_CODE,
                                             new Integer(status));
            _servletHttpRequest.setAttribute(ServletHandler.__J_S_ERROR_MESSAGE,
                                             message);
            
            RequestDispatcher dispatcher=
                _servletHttpRequest.getServletHandler().getServletContext()
                .getRequestDispatcher(error_page);

            try
            {
                ((Dispatcher)dispatcher).error(_servletHttpRequest,this);
            }
            catch(ServletException e)
            {
                log.warn(LogSupport.EXCEPTION,e);
                _httpResponse.sendError(status,message); 
            }
        }
        complete();
    }
770823
def send(self, body, content_type='application/ubjson', timeout=5):
        
        if self.__send_ready.wait(timeout):
            try:
                with self.__send_lock:
                    # access denied response might be received inside send thread rather than here how to best handle?
                    self.__send_channel.basic_publish(msg=Message(body, delivery_mode=2, content_type=content_type),
                                                      exchange=self.__epid)
            except exceptions.AccessRefused as exc:
                raise_from(LinkException('Access denied'), exc)
            except (exceptions.AMQPError, SocketError) as exc:
                raise_from(LinkException('amqp/transport failure'), exc)
            except Exception as exc:  # pylint: disable=broad-except
                raise_from(LinkException('unexpected failure'), exc)
        else:
            exc = self.__send_exc
            if exc:
                raise_from(LinkException('Sender unavailable'), exc)
            else:
                raise LinkException('Sender unavailable (unknown error)')
689806
public static HttpResponse newResponse(RequestContext ctx, HttpStatus status, String message) {
        requireNonNull(ctx, "ctx");
        requireNonNull(status, "status");
        requireNonNull(message, "message");
        return newResponse0(ctx, status, null, message);
    }
125417
public void sendBuf(final String dest, final OtpOutputStream payload)
            throws IOException {
        super.sendBuf(self.pid(), dest, payload);
    }
610821
private void reply(final String response, final boolean error,
            final String errorMessage, final String stackTrace,
            final String statusCode, final int statusCodeInt,
            Map<String, List<String>> responseHeaders) {

        if (!sentReply) {
            // must update sentReply first to avoid duplicated msg.
            sentReply = true;

            final ResponseOnSingeRequest res = new ResponseOnSingeRequest(
                    response, error, errorMessage, stackTrace, statusCode,
                    statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(),
                    responseHeaders);
            if (!getContext().system().deadLetters().equals(sender)) {
                sender.tell(res, getSelf());
            }
            if (getContext() != null) {
                getContext().stop(getSelf());
            }
        }

    }
624480
public synchronized void sendResponse(BinaryResponse response) {
        if (pending == null) {
            pending = new LinkedList<ByteBuffer>();
        }
        pending.add(response.getBuffer());
    }
942804
private ByteBuf writeResponse(ByteBuf buffer, Object request, ThreadContext context) {
    context.serializer().writeObject(request, OUTPUT.get().setByteBuf(buffer));
    return buffer;
  }
1136118
public ChannelFuture respondBinary(ByteBuf byteBuf) throws Exception {
        if (HttpUtil.isTransferEncodingChunked(response)) {
            respondHeadersOnlyForFirstChunk();
            return channel.writeAndFlush(new DefaultHttpContent(byteBuf));
        } else {
            if (!response.headers().contains(CONTENT_TYPE))
                response.headers().set(CONTENT_TYPE, "application/octet-stream");

            response.headers().set(CONTENT_LENGTH, byteBuf.readableBytes());
            response.content().writeBytes(byteBuf);
            return respond();
        }
    }
1137073
protected Response httpPut(String path, String body, int status) {
        return httpRequest(status, null).body(body).put(baseURL + PATH_PREFIX + path);
    }
105947
private void setResponse(int statusCode, String statusMessage, String responseBody, Map<String, List<String>> responseHeaders)
    {
        mStatusCode      = statusCode;
        mStatusMessage   = statusMessage;
        mResponseBody    = responseBody;
        mResponseHeaders = responseHeaders;
    }
525177
private void sendReply(Response<ByteString> response) {
    if (!replied.compareAndSet(false, true)) {
      LOGGER.warn("Already replied to ongoing request {} - spurious response {}", request, response);
    } else {
      final HttpServletResponse httpResponse = (HttpServletResponse) asyncContext.getResponse();

      final StatusType status = response.status();
      httpResponse.setStatus(status.code(), status.reasonPhrase());

      response.headerEntries().forEach(entry ->
          httpResponse.addHeader(entry.getKey(), entry.getValue()));

      response.payload().ifPresent(payload -> {
        try {
          payload.write(httpResponse.getOutputStream());
        } catch (IOException e) {
          LOGGER.warn("Failed to write response", e);
        }
      });

      asyncContext.complete();

      logger.accept(this, Optional.of(response));
    }
  }
905185
public static void sendResponse(HttpRequest request,
            IOSubchannel channel, HttpStatus status) {
        sendResponse(request, channel, status.statusCode(),
            status.reasonPhrase());
    }
854632
function send (req, res, status, headers, message) {
  function write () {
    // response body
    var body = createHtmlDocument(message)

    // response status
    res.statusCode = status
    res.statusMessage = statuses[status]

    // response headers
    setHeaders(res, headers)

    // security headers
    res.setHeader('Content-Security-Policy', "default-src 'none'")
    res.setHeader('X-Content-Type-Options', 'nosniff')

    // standard headers
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))

    if (req.method === 'HEAD') {
      res.end()
      return
    }

    res.end(body, 'utf8')
  }

  if (isFinished(req)) {
    write()
    return
  }

  // unpipe everything from the request
  unpipe(req)

  // flush the request
  onFinished(req, write)
  req.resume()
}
734580
public static void sendAndCloseNoEntityBodyResp(ChannelHandlerContext ctx, HttpResponseStatus status,
            HttpVersion httpVersion, String serverName) {
        HttpResponse outboundResponse = new DefaultHttpResponse(httpVersion, status);
        outboundResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        outboundResponse.headers().set(HttpHeaderNames.CONNECTION.toString(), Constants.CONNECTION_CLOSE);
        outboundResponse.headers().set(HttpHeaderNames.SERVER.toString(), serverName);
        ChannelFuture outboundRespFuture = ctx.channel().writeAndFlush(outboundResponse);
        outboundRespFuture.addListener(
                (ChannelFutureListener) channelFuture -> LOG.warn("Failed to send {}", status.reasonPhrase()));
        ctx.channel().close();
    }