use of io.netty.handler.codec.http.HttpResponseStatus in project asterixdb by apache.
the class QueryResultApiServlet method get.
@Override
protected void get(IServletRequest request, IServletResponse response) throws Exception {
// TODO this seems wrong ...
HttpUtil.setContentType(response, HttpUtil.ContentType.TEXT_HTML, HttpUtil.Encoding.UTF8);
PrintWriter out = response.writer();
final String strHandle = localPath(request);
final ResultHandle handle = ResultHandle.parse(strHandle);
if (handle == null) {
response.setStatus(HttpResponseStatus.BAD_REQUEST);
return;
}
IHyracksDataset hds = getHyracksDataset();
ResultReader resultReader = new ResultReader(hds, handle.getJobId(), handle.getResultSetId());
try {
DatasetJobRecord.Status status = resultReader.getStatus();
final HttpResponseStatus httpStatus;
if (status == null) {
httpStatus = HttpResponseStatus.NOT_FOUND;
} else {
switch(status.getState()) {
case SUCCESS:
httpStatus = HttpResponseStatus.OK;
break;
case RUNNING:
case IDLE:
case FAILED:
httpStatus = HttpResponseStatus.NOT_FOUND;
break;
default:
httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
break;
}
}
response.setStatus(httpStatus);
if (httpStatus != HttpResponseStatus.OK) {
return;
}
// QQQ The output format is determined by the initial
// query and cannot be modified here, so calling back to
// initResponse() is really an error. We need to find a
// way to send the same OutputFormat value here as was
// originally determined there. Need to save this value on
// some object that we can obtain here.
SessionOutput sessionOutput = RestApiServlet.initResponse(request, response);
ResultUtil.printResults(appCtx, resultReader, sessionOutput, new Stats(), null);
} catch (HyracksDataException e) {
final int errorCode = e.getErrorCode();
if (ErrorCode.NO_RESULTSET == errorCode) {
LOGGER.log(Level.INFO, "No results for: \"" + strHandle + "\"");
response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
response.setStatus(HttpResponseStatus.BAD_REQUEST);
out.println(e.getMessage());
LOGGER.log(Level.WARNING, "Error retrieving result for \"" + strHandle + "\"", e);
} catch (Exception e) {
response.setStatus(HttpResponseStatus.BAD_REQUEST);
LOGGER.log(Level.WARNING, "Error retrieving result for \"" + strHandle + "\"", e);
}
if (out.checkError()) {
LOGGER.warning("Error flushing output writer for \"" + strHandle + "\"");
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project riposte by Nike-Inc.
the class ResponseSender method createActualResponseObjectForFirstChunk.
protected HttpResponse createActualResponseObjectForFirstChunk(ResponseInfo<?> responseInfo, ObjectMapper serializer, ChannelHandlerContext ctx) {
HttpResponse actualResponseObject;
HttpResponseStatus httpStatus = HttpResponseStatus.valueOf(responseInfo.getHttpStatusCodeWithDefault(DEFAULT_HTTP_STATUS_CODE));
determineAndSetCharsetAndMimeTypeForResponseInfoIfNecessary(responseInfo);
if (responseInfo.isChunkedResponse()) {
// Chunked response. No content (yet).
actualResponseObject = new DefaultHttpResponse(HTTP_1_1, httpStatus);
} else {
// Full response. There may or may not be content.
if (responseInfo.getContentForFullResponse() == null) {
// No content, so create a simple full response.
actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus);
} else {
// There is content. If it's a raw byte buffer then use it as-is. Otherwise serialize it to a string
// using the provided serializer.
Object content = responseInfo.getContentForFullResponse();
ByteBuf bytesForResponse;
if (content instanceof byte[])
bytesForResponse = Unpooled.wrappedBuffer((byte[]) content);
else {
bytesForResponse = Unpooled.copiedBuffer(serializeOutput(responseInfo.getContentForFullResponse(), serializer, responseInfo, ctx), responseInfo.getDesiredContentWriterEncoding());
}
// Turn the serialized string to bytes for the response content, create the full response with content,
// and set the content type header.
actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus, bytesForResponse);
}
}
return actualResponseObject;
}
use of io.netty.handler.codec.http.HttpResponseStatus in project xipki by xipki.
the class HttpScepServlet method service.
@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
HttpVersion version = request.protocolVersion();
HttpMethod method = request.method();
boolean viaPost;
if (method == HttpMethod.POST) {
viaPost = true;
} else if (method == HttpMethod.GET) {
viaPost = false;
} else {
return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
}
String scepName = null;
String certProfileName = null;
if (servletUri.getPath().length() > 1) {
String scepPath = servletUri.getPath();
if (scepPath.endsWith(CGI_PROGRAM)) {
// skip also the first char (which is always '/')
String path = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
String[] tokens = path.split("/");
if (tokens.length == 2) {
scepName = tokens[0];
certProfileName = tokens[1].toLowerCase();
}
}
// end if
}
if (scepName == null || certProfileName == null) {
return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
}
AuditService auditService = auditServiceRegister.getAuditService();
AuditEvent event = new AuditEvent(new Date());
event.setApplicationName("SCEP");
event.setName(CaAuditConstants.NAME_PERF);
event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name());
String msgId = RandomUtil.nextHexLong();
event.addEventData(CaAuditConstants.NAME_mid, msgId);
AuditLevel auditLevel = AuditLevel.INFO;
AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
String auditMessage = null;
try {
if (responderManager == null) {
auditMessage = "responderManager in servlet not configured";
LOG.error(auditMessage);
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
Scep responder = responderManager.getScep(scepName);
if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
LOG.warn(auditMessage);
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
}
String operation = servletUri.getParameter("operation");
event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
if ("PKIOperation".equalsIgnoreCase(operation)) {
CMSSignedData reqMessage;
// parse the request
try {
byte[] content;
if (viaPost) {
content = readContent(request);
} else {
String b64 = servletUri.getParameter("message");
content = Base64.decode(b64);
}
reqMessage = new CMSSignedData(content);
} catch (Exception ex) {
final String msg = "invalid request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
}
ContentInfo ci;
try {
ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
} catch (MessageDecodingException ex) {
final String msg = "could not decrypt and/or verify the request";
LogUtil.error(LOG, ex, msg);
auditMessage = msg;
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
} catch (OperationException ex) {
ErrorCode code = ex.getErrorCode();
HttpResponseStatus httpCode;
switch(code) {
case ALREADY_ISSUED:
case CERT_REVOKED:
case CERT_UNREVOKED:
httpCode = HttpResponseStatus.FORBIDDEN;
break;
case BAD_CERT_TEMPLATE:
case BAD_REQUEST:
case BAD_POP:
case INVALID_EXTENSION:
case UNKNOWN_CERT:
case UNKNOWN_CERT_PROFILE:
httpCode = HttpResponseStatus.BAD_REQUEST;
break;
case NOT_PERMITTED:
httpCode = HttpResponseStatus.UNAUTHORIZED;
break;
case SYSTEM_UNAVAILABLE:
httpCode = HttpResponseStatus.SERVICE_UNAVAILABLE;
break;
case CRL_FAILURE:
case DATABASE_FAILURE:
case SYSTEM_FAILURE:
httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
break;
default:
httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
break;
}
auditMessage = ex.getMessage();
LogUtil.error(LOG, ex, auditMessage);
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, httpCode);
}
byte[] bodyBytes = ci.getEncoded();
return createOKResponse(version, CT_RESPONSE, bodyBytes);
} else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] caCapsBytes = responder.getCaCaps().getBytes();
return createOKResponse(version, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
} else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] respBytes = responder.getCaCertResp().getBytes();
return createOKResponse(version, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
} else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
auditMessage = "SCEP operation '" + operation + "' is not permitted";
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.FORBIDDEN);
} else {
auditMessage = "unknown SCEP operation '" + operation + "'";
auditStatus = AuditStatus.FAILED;
return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
}
} catch (Throwable th) {
if (th instanceof EOFException) {
final String msg = "connection reset by peer";
if (LOG.isWarnEnabled()) {
LogUtil.warn(LOG, th, msg);
}
LOG.debug(msg, th);
} else {
LOG.error("Throwable thrown, this should not happen!", th);
}
auditLevel = AuditLevel.ERROR;
auditStatus = AuditStatus.FAILED;
auditMessage = "internal error";
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
} finally {
audit(auditService, event, auditLevel, auditStatus, auditMessage);
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project xipki by xipki.
the class HealthCheckServlet method service0.
private FullHttpResponse service0(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession) {
HttpVersion version = request.protocolVersion();
HttpMethod method = request.method();
if (method != HttpMethod.GET) {
return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
}
try {
if (responderManager == null) {
LOG.error("responderManager in servlet is not configured");
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
String caName = null;
X509CaCmpResponder responder = null;
if (servletUri.getPath().length() > 1) {
// skip the first char which is always '/'
String caAlias = servletUri.getPath().substring(1);
caName = responderManager.getCaNameForAlias(caAlias);
if (caName == null) {
caName = caAlias.toLowerCase();
}
responder = responderManager.getX509CaResponder(caName);
}
if (caName == null || responder == null || !responder.isOnService()) {
String auditMessage;
if (caName == null) {
auditMessage = "no CA is specified";
} else if (responder == null) {
auditMessage = "unknown CA '" + caName + "'";
} else {
auditMessage = "CA '" + caName + "' is out of service";
}
LOG.warn(auditMessage);
return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
}
HealthCheckResult healthResult = responder.healthCheck();
HttpResponseStatus status = healthResult.isHealthy() ? HttpResponseStatus.OK : HttpResponseStatus.INTERNAL_SERVER_ERROR;
byte[] respBytes = healthResult.toJsonMessage(true).getBytes();
return createResponse(version, status, HealthCheckServlet.CT_RESPONSE, respBytes);
} catch (Throwable th) {
if (th instanceof EOFException) {
LogUtil.warn(LOG, th, "connection reset by peer");
} else {
LOG.error("Throwable thrown, this should not happen!", th);
}
return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project xipki by xipki.
the class HttpRestServlet method service.
@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) {
HttpVersion version = request.protocolVersion();
HttpMethod method = request.method();
if (method != HttpMethod.POST && method != HttpMethod.GET) {
return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
}
AuditEvent event = new AuditEvent(new Date());
try {
Rest rest = responderManager.getRest();
HttpRequestMetadataRetriever httpRetriever = new HttpRequestMetadataRetrieverImpl(request, servletUri, sslSession, sslReverseProxyMode);
byte[] requestBytes = readContent(request);
RestResponse response = rest.service(servletUri.getPath(), event, requestBytes, httpRetriever);
HttpResponseStatus status = HttpResponseStatus.valueOf(response.getStatusCode());
FullHttpResponse resp = createResponse(version, status, response.getContentType(), response.getBody());
for (String headerName : response.getHeaders().keySet()) {
resp.headers().add(headerName, response.getHeaders().get(headerName));
}
return resp;
} finally {
event.finish();
auditServiceRegister.getAuditService().logEvent(event);
}
}
Aggregations