in server/src/main/java/org/apache/calcite/avatica/server/AvaticaJsonHandler.java [88:156]
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try (Context ctx = requestTimer.start()) {
if (!isUserPermitted(serverConfig, baseRequest, request, response)) {
LOG.debug("HTTP request from {} is unauthenticated and authentication is required",
request.getRemoteAddr());
return;
}
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
if (request.getMethod().equals("POST")) {
// First look for a request in the header, then look in the body.
// The latter allows very large requests without hitting HTTP 413.
String rawRequest = request.getHeader("request");
if (rawRequest == null) {
// Avoid a new buffer creation for every HTTP request
final UnsynchronizedBuffer buffer = threadLocalBuffer.get();
try (ServletInputStream inputStream = request.getInputStream()) {
byte[] bytes = AvaticaUtils.readFullyToBytes(inputStream, buffer);
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
rawRequest = AvaticaUtils.newString(bytes, encoding);
} finally {
// Reset the offset into the buffer after we're done
buffer.reset();
}
}
final String jsonRequest = rawRequest;
LOG.trace("request: {}", jsonRequest);
HandlerResponse<String> jsonResponse;
try {
if (null != serverConfig && serverConfig.supportsImpersonation()) {
String remoteUser = serverConfig.getRemoteUserExtractor().extract(request);
jsonResponse = serverConfig.doAsRemoteUser(remoteUser,
request.getRemoteAddr(), new Callable<HandlerResponse<String>>() {
@Override public HandlerResponse<String> call() {
return jsonHandler.apply(jsonRequest);
}
});
} else {
jsonResponse = jsonHandler.apply(jsonRequest);
}
} catch (RemoteUserExtractionException e) {
LOG.debug("Failed to extract remote user from request", e);
jsonResponse = jsonHandler.unauthenticatedErrorResponse(e);
} catch (RemoteUserDisallowedException e) {
LOG.debug("Remote user is not authorized", e);
jsonResponse = jsonHandler.unauthorizedErrorResponse(e);
} catch (BadRequestException e) {
LOG.debug("Bad request exception", e);
jsonResponse = jsonHandler.badRequestErrorResponse(e);
} catch (Exception e) {
LOG.debug("Error invoking request from {}", baseRequest.getRemoteAddr(), e);
jsonResponse = jsonHandler.convertToErrorResponse(e);
}
LOG.trace("response: {}", jsonResponse);
baseRequest.setHandled(true);
// Set the status code and write out the response.
response.setStatus(jsonResponse.getStatusCode());
response.getWriter().println(jsonResponse.getResponse());
}
}
}