static void sendError(HttpServerExchange exchange, boolean isGet, boolean encode, String msg) { if (encode) { try { ModelNode response = new ModelNode(); response.set(msg); ByteArrayOutputStream bout = new ByteArrayOutputStream(); response.writeBase64(bout); byte[] bytes = bout.toByteArray(); exchange .getResponseHeaders() .put(Headers.CONTENT_TYPE, APPLICATION_DMR_ENCODED + ";" + UTF_8); exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(bytes.length)); exchange.setResponseCode(500); exchange.getResponseSender().send(new String(bytes), IoCallback.END_EXCHANGE); } catch (IOException e) { // fallback, should not happen sendError(exchange, isGet, false, msg); } } else { byte[] bytes = msg.getBytes(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, TEXT_PLAIN + ";" + UTF_8); exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(bytes.length)); exchange.setResponseCode(500); exchange.getResponseSender().send(msg, IoCallback.END_EXCHANGE); } }
/** * 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); } }
@Override public long getContentLength() { // Needed for the http client final ByteArrayOutputStream os = new ByteArrayOutputStream(); try { model.writeBase64(os); return os.size(); } catch (Exception e) { return -1; } }
@Override public void writeTo(OutputStream out) throws IOException { model.writeBase64(out); }