Esempio n. 1
0
  /**
   * Writes the HTTP response to the output stream.
   *
   * @param http The HttpExchange object that allows access to the request and response.
   * @param isGet Flag indicating whether or not the request was a GET request or POST request.
   * @param pretty Flag indicating whether or not the output, if JSON, should be pretty printed or
   *     not.
   * @param response The DMR response from the operation.
   * @param status The HTTP status code to be included in the response.
   * @param encode Flag indicating whether or not to Base64 encode the response payload.
   * @throws IOException if an error occurs while attempting to generate the HTTP response.
   */
  private void writeResponse(
      final HttpExchange http,
      boolean isGet,
      boolean pretty,
      ModelNode response,
      int status,
      boolean encode,
      String contentType)
      throws IOException {
    final Headers responseHeaders = http.getResponseHeaders();
    responseHeaders.add(CONTENT_TYPE, contentType);
    http.sendResponseHeaders(status, 0);

    final OutputStream out = http.getResponseBody();
    final PrintWriter print = new PrintWriter(out);

    // GET (read) operations will never have a compensating update, and the status is already
    // available via the http response status code, so unwrap them.
    if (isGet && status == OK) response = response.get("result");

    try {
      if (encode) {
        response.writeBase64(out);
      } else {
        response.writeJSONString(print, !pretty);
      }
    } finally {
      print.flush();
      out.flush();
      safeClose(print);
      safeClose(out);
    }
  }