use of io.netty.handler.codec.http.HttpResponseStatus in project elasticsearch by elastic.
the class Netty4HttpChannel method newResponse.
// Create a new {@link HttpResponse} to transmit the response for the netty request.
private FullHttpResponse newResponse(ByteBuf buffer) {
final boolean http10 = isHttp10();
final boolean close = isCloseConnection();
// Build the response object.
// default to initialize
final HttpResponseStatus status = HttpResponseStatus.OK;
final FullHttpResponse response;
if (http10) {
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, status, buffer);
if (!close) {
response.headers().add(HttpHeaderNames.CONNECTION, "Keep-Alive");
}
} else {
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
}
return response;
}
use of io.netty.handler.codec.http.HttpResponseStatus in project jersey by jersey.
the class NettyResponseWriter method writeResponseStatusAndHeaders.
@Override
public synchronized OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException {
if (responseWritten) {
LOGGER.log(Level.FINE, "Response already written.");
return null;
}
responseWritten = true;
String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
int statusCode = responseContext.getStatus();
HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode) : new HttpResponseStatus(statusCode, reasonPhrase);
DefaultHttpResponse response;
if (contentLength == 0) {
response = new DefaultFullHttpResponse(req.protocolVersion(), status);
} else {
response = new DefaultHttpResponse(req.protocolVersion(), status);
}
for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
response.headers().add(e.getKey(), e.getValue());
}
if (contentLength == -1) {
HttpUtil.setTransferEncodingChunked(response, true);
} else {
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
}
if (HttpUtil.isKeepAlive(req)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ctx.writeAndFlush(response);
if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {
JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());
if (HttpUtil.isTransferEncodingChunked(response)) {
ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
} else {
ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
}
return jerseyChunkedInput;
} else {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
return null;
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project asterixdb by apache.
the class QueryServiceServlet method handleRequest.
private void handleRequest(RequestParameters param, IServletResponse response) throws IOException {
LOGGER.info(param.toString());
long elapsedStart = System.nanoTime();
final StringWriter stringWriter = new StringWriter();
final PrintWriter resultWriter = new PrintWriter(stringWriter);
ResultDelivery delivery = parseResultDelivery(param.mode);
String handleUrl = getHandleUrl(param.host, param.path, delivery);
SessionOutput sessionOutput = createSessionOutput(param, handleUrl, resultWriter);
SessionConfig sessionConfig = sessionOutput.config();
HttpUtil.setContentType(response, HttpUtil.ContentType.APPLICATION_JSON, HttpUtil.Encoding.UTF8);
HttpResponseStatus status = HttpResponseStatus.OK;
Stats stats = new Stats();
long[] execStartEnd = new long[] { -1, -1 };
resultWriter.print("{\n");
printRequestId(resultWriter);
printClientContextID(resultWriter, param);
printSignature(resultWriter);
printType(resultWriter, sessionConfig);
try {
if (param.statement == null || param.statement.isEmpty()) {
throw new AsterixException("Empty request, no statement provided");
}
String statementsText = param.statement + ";";
executeStatement(statementsText, sessionOutput, delivery, stats, param, handleUrl, execStartEnd);
if (ResultDelivery.IMMEDIATE == delivery || ResultDelivery.DEFERRED == delivery) {
ResultUtil.printStatus(sessionOutput, ResultStatus.SUCCESS);
}
} catch (AlgebricksException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
GlobalConfig.ASTERIX_LOGGER.log(Level.INFO, pe.getMessage(), pe);
ResultUtil.printError(resultWriter, pe);
ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
status = HttpResponseStatus.BAD_REQUEST;
} catch (HyracksException pe) {
GlobalConfig.ASTERIX_LOGGER.log(Level.WARNING, pe.getMessage(), pe);
ResultUtil.printError(resultWriter, pe);
ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, "Unexpected exception", e);
ResultUtil.printError(resultWriter, e);
ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
} finally {
if (execStartEnd[0] == -1) {
execStartEnd[1] = -1;
} else if (execStartEnd[1] == -1) {
execStartEnd[1] = System.nanoTime();
}
}
printMetrics(resultWriter, System.nanoTime() - elapsedStart, execStartEnd[1] - execStartEnd[0], stats.getCount(), stats.getSize());
resultWriter.print("}\n");
resultWriter.flush();
String result = stringWriter.toString();
GlobalConfig.ASTERIX_LOGGER.log(Level.FINE, result);
response.setStatus(status);
response.writer().print(result);
if (response.writer().checkError()) {
LOGGER.warning("Error flushing output writer");
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project asterixdb by apache.
the class QueryStatusApiServlet method get.
@Override
protected void get(IServletRequest request, IServletResponse response) throws Exception {
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());
final DatasetJobRecord.Status resultReaderStatus = resultReader.getStatus();
if (resultReaderStatus == null) {
LOGGER.log(Level.INFO, "No results for: \"" + strHandle + "\"");
response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
ResultStatus resultStatus = resultStatus(resultReaderStatus);
Exception ex = extractException(resultReaderStatus);
final StringWriter stringWriter = new StringWriter();
final PrintWriter resultWriter = new PrintWriter(stringWriter);
HttpUtil.setContentType(response, HttpUtil.ContentType.APPLICATION_JSON, HttpUtil.Encoding.UTF8);
HttpResponseStatus httpStatus = HttpResponseStatus.OK;
resultWriter.print("{\n");
ResultUtil.printStatus(resultWriter, resultStatus, (ex != null) || ResultStatus.SUCCESS == resultStatus);
if (ResultStatus.SUCCESS == resultStatus) {
String servletPath = servletPath(request).replace("status", "result");
String resHandle = "http://" + host(request) + servletPath + strHandle;
printHandle(resultWriter, resHandle, false);
} else if (ex != null) {
ResultUtil.printError(resultWriter, ex, false);
}
resultWriter.print("}\n");
resultWriter.flush();
String result = stringWriter.toString();
response.setStatus(httpStatus);
response.writer().print(result);
if (response.writer().checkError()) {
LOGGER.warning("Error flushing output writer");
}
}
use of io.netty.handler.codec.http.HttpResponseStatus in project netty by netty.
the class HttpConversionUtil method toHttpResponse.
/**
* Create a new object to contain the response data
*
* @param streamId The stream associated with the response
* @param http2Headers The initial set of HTTP/2 headers to create the response with
* @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
* @param validateHttpHeaders <ul>
* <li>{@code true} to validate HTTP headers in the http-codec</li>
* <li>{@code false} not to validate HTTP headers in the http-codec</li>
* </ul>
* @return A new response object which represents headers/data
* @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
*/
public static FullHttpResponse toHttpResponse(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc, boolean validateHttpHeaders) throws Http2Exception {
HttpResponseStatus status = parseStatus(http2Headers.status());
// HTTP/2 does not define a way to carry the version or reason phrase that is included in an
// HTTP/1.1 status line.
FullHttpResponse msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, alloc.buffer(), validateHttpHeaders);
try {
addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
} catch (Http2Exception e) {
msg.release();
throw e;
} catch (Throwable t) {
msg.release();
throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
}
return msg;
}
Aggregations