Search in sources :

Example 1 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.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;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 2 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.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;
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) List(java.util.List) Map(java.util.Map) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput)

Example 3 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.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");
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) SessionConfig(org.apache.asterix.translator.SessionConfig) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) ResultDelivery(org.apache.asterix.translator.IStatementExecutor.ResultDelivery) AsterixException(org.apache.asterix.common.exceptions.AsterixException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) AsterixException(org.apache.asterix.common.exceptions.AsterixException) StringWriter(java.io.StringWriter) SessionOutput(org.apache.asterix.translator.SessionOutput) Stats(org.apache.asterix.translator.IStatementExecutor.Stats) PrintWriter(java.io.PrintWriter)

Example 4 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.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");
    }
}
Also used : ResultReader(org.apache.asterix.app.result.ResultReader) StringWriter(java.io.StringWriter) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DatasetJobRecord(org.apache.hyracks.api.dataset.DatasetJobRecord) ResultHandle(org.apache.asterix.app.result.ResultHandle) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) PrintWriter(java.io.PrintWriter)

Example 5 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.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;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Aggregations

HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)73 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)17 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)16 ByteBuf (io.netty.buffer.ByteBuf)15 HttpMethod (io.netty.handler.codec.http.HttpMethod)11 IOException (java.io.IOException)11 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)10 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpVersion (io.netty.handler.codec.http.HttpVersion)9 Map (java.util.Map)8 URI (java.net.URI)7 Test (org.junit.Test)7 URISyntaxException (java.net.URISyntaxException)6 Test (org.junit.jupiter.api.Test)6 Channel (io.netty.channel.Channel)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)5 Duration (java.time.Duration)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4