class DefaultHttpResponseSender extends ComponentSupport implements HttpResponseSender {

  @Override
  public void send(@Nullable final Request request, final Response response, final HttpServletResponse httpResponse)
      throws ServletException, IOException
  {
    log.debug("Sending response: {}", response);

    // add response headers
    for (Map.Entry<String, String> header : response.getHeaders()) {
      httpResponse.addHeader(header.getKey(), header.getValue());
    }

    // add status followed by payload if we have one
    Status status = response.getStatus();
    String statusMessage = status.getMessage();
    try (Payload payload = response.getPayload()) {
      if (status.isSuccessful() || payload != null) {

        if (statusMessage == null) {
          httpResponse.setStatus(status.getCode());
        }
        else {
          httpResponse.setStatus(status.getCode(), statusMessage);
        }

        if (payload != null) {
          log.trace("Attaching payload: {}", payload);

          if (payload.getContentType() != null) {
            httpResponse.setContentType(payload.getContentType());
          }
          if (payload.getSize() != Payload.UNKNOWN_SIZE) {
            httpResponse.setContentLengthLong(payload.getSize());
          }

          if (request != null && !HttpMethods.HEAD.equals(request.getAction())) {
            try (InputStream input = payload.openInputStream(); OutputStream output = httpResponse.getOutputStream()) {
              payload.copy(input, output);
            }
          }
        }
      }
      else {
        httpResponse.sendError(status.getCode(), statusMessage);
      }
    }
  }

}