Example usage for io.netty.handler.codec.http HttpResponseStatus INTERNAL_SERVER_ERROR

List of usage examples for io.netty.handler.codec.http HttpResponseStatus INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus INTERNAL_SERVER_ERROR.

Prototype

HttpResponseStatus INTERNAL_SERVER_ERROR

To view the source code for io.netty.handler.codec.http HttpResponseStatus INTERNAL_SERVER_ERROR.

Click Source Link

Document

500 Internal Server Error

Usage

From source file:cf.component.http.RequestException.java

License:Open Source License

public RequestException(Throwable cause) {
    this(HttpResponseStatus.INTERNAL_SERVER_ERROR, cause);
}

From source file:cn.wantedonline.puppy.httpserver.handler.TextResponseHandler.java

License:Apache License

public void logThrowable(final ContextAttachment attach, final HttpRequest request, final HttpResponse response,
        final Throwable ex) {
    response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

    if (logThrowableIgnoreList.contains(ex.getClass().getName())) {
        return;/*w w  w . j  av a2 s  . com*/
    }

    logError(request.getPath(), "{}:{} |{}\n\n{}", ex.getClass().getSimpleName(), request.getPath(),
            ManagementFactory.getRuntimeMXBean().getName(), request.getDetailInfo(), ex);
}

From source file:com.addthis.hydra.query.web.HttpQueryHandler.java

License:Apache License

private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv)
        throws Exception {
    StringBuilderWriter writer = new StringBuilderWriter(50);
    HttpResponse response = HttpUtils.startResponse(writer);
    response.headers().add("Access-Control-Allow-Origin", "*");

    switch (target) {
    case "/metrics":
        fakeMetricsServlet.writeMetrics(writer, kv);
        break;/*  w ww  . ja  va  2s .  co  m*/
    case "/query/list":
        writer.write("[\n");
        for (QueryEntryInfo stat : tracker.getRunning()) {
            writer.write(CodecJSON.encodeString(stat).concat(",\n"));
        }
        writer.write("]");
        break;
    case "/completed/list":
        writer.write("[\n");
        for (QueryEntryInfo stat : tracker.getCompleted()) {
            writer.write(CodecJSON.encodeString(stat).concat(",\n"));
        }
        writer.write("]");
        break;
    case "/v2/host/list":
    case "/host/list":
        String queryStatusUuid = kv.getValue("uuid");
        QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid);
        if (queryEntry != null) {
            DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request,
                    queryEntry);
            hostDetailsHandler.handle();
            return;
        } else {
            QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid);
            if (queryEntryInfo != null) {
                JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo);
                writer.write(entryJSON.toString());
            } else {
                throw new RuntimeException("could not find query");
            }
            break;
        }
    case "/query/cancel":
        if (tracker.cancelRunning(kv.getValue("uuid"))) {
            writer.write("canceled " + kv.getValue("uuid"));
        } else {
            writer.write("canceled failed for " + kv.getValue("uuid"));
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        break;
    case "/query/encode": {
        Query q = new Query(null, kv.getValue("query", kv.getValue("path", "")), null);
        JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path");
        writer.write(path.toString());
        break;
    }
    case "/query/decode": {
        String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}";
        Query q = CodecJSON.decodeString(new Query(), qo);
        writer.write(q.getPaths()[0]);
        break;
    }
    case "/v2/queries/finished.list": {
        JSONArray runningEntries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getCompleted()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            //TODO: replace this with some high level summary
            entryJSON.put("hostInfoSet", "");
            runningEntries.put(entryJSON);
        }
        writer.write(runningEntries.toString());
        break;
    }
    case "/v2/queries/running.list": {
        JSONArray runningEntries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getRunning()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            //TODO: replace this with some high level summary
            entryJSON.put("hostInfoSet", "");
            runningEntries.put(entryJSON);
        }
        writer.write(runningEntries.toString());
        break;
    }
    case "/v2/queries/workers": {
        JSONObject jsonObject = new JSONObject();
        for (WorkerData workerData : meshQueryMaster.worky().values()) {
            jsonObject.put(workerData.hostName, workerData.queryLeases.availablePermits());
        }
        writer.write(jsonObject.toString());
        break;
    }
    case "/v2/queries/list":
        JSONArray queries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getCompleted()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            entryJSON.put("state", 0);
            queries.put(entryJSON);
        }
        for (QueryEntryInfo entryInfo : tracker.getRunning()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            entryJSON.put("state", 3);
            queries.put(entryJSON);
        }
        writer.write(queries.toString());
        break;
    case "/v2/job/list": {
        StringWriter swriter = new StringWriter();
        final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter);
        json.writeStartArray();
        for (IJob job : meshQueryMaster.keepy().getJobs()) {
            if (job.getQueryConfig() != null && job.getQueryConfig().getCanQuery()) {
                List<JobTask> tasks = job.getCopyOfTasks();
                String uuid = job.getId();
                json.writeStartObject();
                json.writeStringField("id", uuid);
                json.writeStringField("description", Optional.fromNullable(job.getDescription()).or(""));
                json.writeNumberField("state", job.getState().ordinal());
                json.writeStringField("creator", job.getCreator());
                json.writeNumberField("submitTime", Optional.fromNullable(job.getSubmitTime()).or(-1L));
                json.writeNumberField("startTime", Optional.fromNullable(job.getStartTime()).or(-1L));
                json.writeNumberField("endTime", Optional.fromNullable(job.getStartTime()).or(-1L));
                json.writeNumberField("replicas", Optional.fromNullable(job.getReplicas()).or(0));
                json.writeNumberField("backups", Optional.fromNullable(job.getBackups()).or(0));
                json.writeNumberField("nodes", tasks.size());
                json.writeEndObject();
            }
        }
        json.writeEndArray();
        json.close();
        writer.write(swriter.toString());
        break;
    }
    case "/v2/settings/git.properties": {
        StringWriter swriter = new StringWriter();
        final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter);
        Properties gitProperties = new Properties();
        json.writeStartObject();
        try {
            InputStream in = queryServer.getClass().getResourceAsStream("/git.properties");
            gitProperties.load(in);
            in.close();
            json.writeStringField("commitIdAbbrev", gitProperties.getProperty("git.commit.id.abbrev"));
            json.writeStringField("commitUserEmail", gitProperties.getProperty("git.commit.user.email"));
            json.writeStringField("commitMessageFull", gitProperties.getProperty("git.commit.message.full"));
            json.writeStringField("commitId", gitProperties.getProperty("git.commit.id"));
            json.writeStringField("commitUserName", gitProperties.getProperty("git.commit.user.name"));
            json.writeStringField("buildUserName", gitProperties.getProperty("git.build.user.name"));
            json.writeStringField("commitIdDescribe", gitProperties.getProperty("git.commit.id.describe"));
            json.writeStringField("buildUserEmail", gitProperties.getProperty("git.build.user.email"));
            json.writeStringField("branch", gitProperties.getProperty("git.branch"));
            json.writeStringField("commitTime", gitProperties.getProperty("git.commit.time"));
            json.writeStringField("buildTime", gitProperties.getProperty("git.build.time"));
        } catch (Exception ex) {
            log.warn("Error loading git.properties, possibly jar was not compiled with maven.");
        }
        json.writeEndObject();
        json.close();
        writer.write(swriter.toString());
        break;
    }
    default:
        // forward to static file server
        ctx.pipeline().addLast(staticFileHandler);
        request.retain();
        ctx.fireChannelRead(request);
        return; // don't do text response clean up
    }
    log.trace("response being sent {}", writer);
    ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()),
            CharsetUtil.UTF_8);
    HttpContent content = new DefaultHttpContent(textResponse);
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ctx.write(content);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    log.trace("response pending");
    if (!HttpHeaders.isKeepAlive(request)) {
        log.trace("Setting close listener");
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

private static final FullHttpResponse http_500(String errorMessage) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(errorMessage.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest msg) throws Exception {

    final RequestHandlerMapping mapping = config.getRequestMapping(msg.getUri());

    String relativePath = msg.getUri();

    if (mapping != null) {
        relativePath = relativePath.substring(mapping.path().length());
    }// www .  ja v  a 2  s  .c  o  m

    // Create request/response
    final PooledServerRequest request = messagePool.getRequest();

    // Handle 503 - sanity check, should be caught in acceptor
    if (request == null) {
        sendServerError(ctx, new ServerTooBusyException("Maximum concurrent connections reached"));
        return;
    }

    request.init(ctx.channel(), msg, relativePath);

    final RequestHandler handler = mapping == null ? null : mapping.handler(request);

    final PooledServerResponse response = messagePool.getResponse();
    response.init(ctx, this, handler, request, config.logger());

    if (mapping == null) {
        // No handler found, 404
        response.setStatus(HttpResponseStatus.NOT_FOUND);
    }

    // Store in ChannelHandlerContext for future reference
    ctx.attr(ATTR_RESPONSE).set(response);

    try {

        // MJS: Dispatch an error if not found or authorized
        if (response.getStatus() == HttpResponseStatus.UNAUTHORIZED
                || response.getStatus() == HttpResponseStatus.NOT_FOUND) {
            config.errorHandler().onError(request, response, null);
        } else {
            handler.onRequest(request, response);
        }

    } catch (final Throwable t) {

        // Catch server errors
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

        try {
            config.errorHandler().onError(request, response, t);
        } catch (final Throwable t2) {
            response.write(t.getClass() + " was thrown while processing this request.  Additionally, "
                    + t2.getClass() + " was thrown while handling this exception.");
        }

        config.logger().error(request, response, t);

        // Force request to end on exception, async handlers cannot allow
        // unchecked exceptions and still expect to return data
        if (!response.isFinished()) {
            response.finish();
        }

    } finally {

        // If handler did not request async response, finish request
        if (!response.isFinished() && !response.isSuspended()) {
            response.finish();
        }

    }

}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable exception) throws Exception {

    final PooledServerResponse response = ctx.attr(ATTR_RESPONSE).get();

    if (response != null) {

        try {/*from w  w  w  . j av a2  s . c  om*/

            try {

                if (!response.isFinished()) {

                    response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

                    config.errorHandler().onError(response.request(), response, exception);

                    response.close();

                    final RequestHandler handler = response.handler();

                    if (handler != null) {
                        handler.onException(response.request(), response, exception);
                    }

                }

            } finally {

                config.logger().error(response.request(), response, exception);

            }

        } finally {

            freeHandlers(ctx);

        }

    }

}

From source file:com.barchart.netty.rest.server.Filter.java

License:BSD License

protected void next(final HttpServerRequest request) throws IOException {

    if (next != null) {
        try {/*from  w  w  w .ja  va 2 s.co  m*/
            next.handle(request);
        } catch (final Throwable t) {
            request.response().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            request.response().write("Error executing next handler");
            request.response().finish();
        }
    } else {
        request.response().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        request.response().write("Filter.next() called with no next handler configured");
        request.response().finish();
    }

}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void handle(final HttpServerRequest request) throws IOException {

    final HttpMethod method = request.getMethod();

    try {/*from w w  w  .  j  a v a  2s. c  o m*/
        if (method == HttpMethod.GET) {
            get(request);
        } else if (method == HttpMethod.POST) {
            post(request);
        } else if (method == HttpMethod.PUT) {
            put(request);
        } else if (method == HttpMethod.DELETE) {
            delete(request);
        } else {
            complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED,
                    method.name() + " not implemented");
        }
    } catch (final Throwable t) {
        complete(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, t.getMessage());
    }

}

From source file:com.barchart.netty.server.http.handlers.StaticResourceHandler.java

License:BSD License

@Override
public void handle(final HttpServerRequest request) throws IOException {

    try {/* w w w  .  j a  v  a 2 s .  c  om*/

        final Resource resource = resolver.resolve(request.getPathInfo());

        if (resource.contentType() != null)
            request.response().setContentType(resource.contentType());

        // Set Cache-Control: public
        request.response().headers().add(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.PUBLIC);

        if (!handleCache(request, resource)) {

            // Set modification time
            HttpHeaders.setDateHeader(request.response(), HttpHeaders.Names.LAST_MODIFIED,
                    new Date(resource.modified()));

            request.response().setContentLength((int) resource.size());

            // Chunked response for (potentially) large files
            if (resource.size() == 0 || resource.size() > 8192)
                request.response().setChunkSize(8192);

            IOUtils.copy(resource.stream(), request.response().getOutputStream());

        }

    } catch (final IOException e) {

        request.response().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        request.response().write("500 Server Error");

    } catch (final ResourceNotFoundException e) {

        request.response().setStatus(HttpResponseStatus.NOT_FOUND);
        request.response().write("404 Not Found");

    } finally {

        request.response().finish();

    }

}

From source file:com.barchart.netty.server.http.pipeline.HttpRequestChannelHandler.java

License:BSD License

/**
 * Attempt to send a server error to the client in response to an unchecked
 * exception, swallowing IOExceptions./*from   w ww  . ja v a2 s .  c o m*/
 */
private void sendError(final PooledHttpServerRequest request, final Throwable error) {

    // Catch unchecked exceptions from handlers
    try {

        request.response().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

        try {
            server.errorHandler().onError(request, error);
        } catch (final Throwable t) {
            request.response()
                    .write(error.getClass() + " was thrown while processing this request.  Additionally, "
                            + t.getClass() + " was thrown while handling this exception.");
        }

        // Force request to end on exception, async handlers cannot allow
        // unchecked exceptions and still expect to return data
        if (!request.response().isFinished()) {
            request.response().finish();
        }

    } catch (final IOException ioe) {
        // Pretty likely at this point, swallow it because we don't care
    }

}