Search in sources :

Example 41 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project xian by happyyangyuan.

the class DefaultExceptionHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    LOG.error("Exception caught", cause);
    HttpResponseStatus status = (cause instanceof BadRequestException) ? BAD_REQUEST : INTERNAL_SERVER_ERROR;
    String content = StringUtil.getExceptionStacktrace(cause);
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, Config.getContentType());
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    /*ctx.writeAndFlush(response); todo 爆了异常之后,这里根本写不进去,直接查日志吧!*/
    ctx.close();
    LOG.warn("TODO: 16/9/10 目前是出现了异常则直接关闭,这样对长连接稳定性好像不太有利");
    MsgIdHolder.clear();
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) BadRequestException(info.xiancloud.nettyhttpserver.http.bean.BadRequestException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 42 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project jersey by jersey.

the class NettyHttp2ResponseWriter method writeResponseStatusAndHeaders.

@Override
public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException {
    String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
    int statusCode = responseContext.getStatus();
    HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode) : new HttpResponseStatus(statusCode, reasonPhrase);
    DefaultHttp2Headers response = new DefaultHttp2Headers();
    response.status(Integer.toString(responseContext.getStatus()));
    for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
        response.add(e.getKey().toLowerCase(), e.getValue());
    }
    response.set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(contentLength));
    ctx.writeAndFlush(new DefaultHttp2HeadersFrame(response));
    if (!headersFrame.headers().method().equals(HttpMethod.HEAD.asciiName()) && (contentLength > 0 || contentLength == -1)) {
        return new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                write(new byte[] { (byte) b });
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                ByteBuf buffer = ctx.alloc().buffer(len);
                buffer.writeBytes(b, off, len);
                ctx.writeAndFlush(new DefaultHttp2DataFrame(buffer, false));
            }

            @Override
            public void flush() throws IOException {
                ctx.flush();
            }

            @Override
            public void close() throws IOException {
                ctx.write(new DefaultHttp2DataFrame(true)).addListener(NettyResponseWriter.FLUSH_FUTURE);
            }
        };
    } else {
        ctx.writeAndFlush(new DefaultHttp2DataFrame(true));
        return null;
    }
}
Also used : DefaultHttp2HeadersFrame(io.netty.handler.codec.http2.DefaultHttp2HeadersFrame) DefaultHttp2DataFrame(io.netty.handler.codec.http2.DefaultHttp2DataFrame) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) OutputStream(java.io.OutputStream) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map)

Example 43 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project hadoop by apache.

the class ExceptionHandler method exceptionCaught.

static DefaultFullHttpResponse exceptionCaught(Throwable cause) {
    Exception e = cause instanceof Exception ? (Exception) cause : new Exception(cause);
    if (LOG.isTraceEnabled()) {
        LOG.trace("GOT EXCEPTION", e);
    }
    //Convert exception
    if (e instanceof ParamException) {
        final ParamException paramexception = (ParamException) e;
        e = new IllegalArgumentException("Invalid value for webhdfs parameter \"" + paramexception.getParameterName() + "\": " + e.getCause().getMessage(), e);
    } else if (e instanceof ContainerException || e instanceof SecurityException) {
        e = toCause(e);
    } else if (e instanceof RemoteException) {
        e = ((RemoteException) e).unwrapRemoteException();
    }
    //Map response status
    final HttpResponseStatus s;
    if (e instanceof SecurityException) {
        s = FORBIDDEN;
    } else if (e instanceof AuthorizationException) {
        s = FORBIDDEN;
    } else if (e instanceof FileNotFoundException) {
        s = NOT_FOUND;
    } else if (e instanceof IOException) {
        s = FORBIDDEN;
    } else if (e instanceof UnsupportedOperationException) {
        s = BAD_REQUEST;
    } else if (e instanceof IllegalArgumentException) {
        s = BAD_REQUEST;
    } else {
        LOG.warn("INTERNAL_SERVER_ERROR", e);
        s = INTERNAL_SERVER_ERROR;
    }
    final byte[] js = JsonUtil.toJsonString(e).getBytes(Charsets.UTF_8);
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, s, Unpooled.wrappedBuffer(js));
    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    resp.headers().set(CONTENT_LENGTH, js.length);
    return resp;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) StandbyException(org.apache.hadoop.ipc.StandbyException) ContainerException(com.sun.jersey.api.container.ContainerException) IOException(java.io.IOException) RemoteException(org.apache.hadoop.ipc.RemoteException) FileNotFoundException(java.io.FileNotFoundException) AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) ParamException(com.sun.jersey.api.ParamException) ContainerException(com.sun.jersey.api.container.ContainerException) ParamException(com.sun.jersey.api.ParamException) RemoteException(org.apache.hadoop.ipc.RemoteException)

Example 44 with HttpResponseStatus

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

Example 45 with HttpResponseStatus

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

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