in server/src/main/java/org/apache/calcite/avatica/server/AvaticaProtobufHandler.java [90:155]
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try (Context ctx = this.requestTimer.start()) {
if (!request.getMethod().equals("POST")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getOutputStream().write(
"This server expects only POST calls.".getBytes(StandardCharsets.UTF_8));
baseRequest.setHandled(true);
return;
}
// Check if the user is OK to proceed.
if (!isUserPermitted(serverConfig, baseRequest, request, response)) {
LOG.debug("HTTP request from {} is unauthenticated and authentication is required",
request.getRemoteAddr());
return;
}
final byte[] requestBytes;
// Avoid a new buffer creation for every HTTP request
final UnsynchronizedBuffer buffer = threadLocalBuffer.get();
try (ServletInputStream inputStream = request.getInputStream()) {
requestBytes = AvaticaUtils.readFullyToBytes(inputStream, buffer);
} finally {
buffer.reset();
}
response.setContentType("application/octet-stream;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
HandlerResponse<byte[]> handlerResponse;
try {
if (null != serverConfig && serverConfig.supportsImpersonation()) {
// If we can't extract a user, need to throw 401 in that case.
String remoteUser = serverConfig.getRemoteUserExtractor().extract(request);
// Invoke the ProtobufHandler inside as doAs for the remote user.
// The doAsRemoteUser call may disallow a user, need to throw 403 in that case.
handlerResponse = serverConfig.doAsRemoteUser(remoteUser,
request.getRemoteAddr(), new Callable<HandlerResponse<byte[]>>() {
@Override public HandlerResponse<byte[]> call() {
return pbHandler.apply(requestBytes);
}
});
} else {
handlerResponse = pbHandler.apply(requestBytes);
}
} catch (RemoteUserExtractionException e) {
LOG.debug("Failed to extract remote user from request", e);
handlerResponse = pbHandler.unauthenticatedErrorResponse(e);
} catch (RemoteUserDisallowedException e) {
LOG.debug("Remote user is not authorized", e);
handlerResponse = pbHandler.unauthorizedErrorResponse(e);
} catch (BadRequestException e) {
LOG.debug("Bad request exception", e);
handlerResponse = pbHandler.badRequestErrorResponse(e);
} catch (Exception e) {
LOG.debug("Error invoking request from {}", baseRequest.getRemoteAddr(), e);
// Catch at the highest level of exceptions
handlerResponse = pbHandler.convertToErrorResponse(e);
}
baseRequest.setHandled(true);
response.setStatus(handlerResponse.getStatusCode());
response.getOutputStream().write(handlerResponse.getResponse());
}
}