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

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

Introduction

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

Prototype

public static HttpResponseStatus valueOf(int code) 

Source Link

Document

Returns the HttpResponseStatus represented by the specified code.

Usage

From source file:Http2ClientConnectionHandler.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
        short weight, boolean exclusive, int padding, boolean endStream, boolean endSegment)
        throws Http2Exception {
    if (headers.contains(Http2ExampleUtil.UPGRADE_RESPONSE_HEADER)) {
        System.out.println("Received HTTP/2 response to the HTTP->HTTP/2 upgrade request");
    }/* w  w w .j  ava 2  s  .c  om*/
    final OutstandingRequest outstandingRequest = outstanding.get(streamId);
    if (outstandingRequest != null) {
        for (Map.Entry<String, String> entry : headers.entries()) {
            if (outstandingRequest.status == null && entry.getKey().equals(":status")) {
                outstandingRequest.status = HttpResponseStatus.valueOf(Integer.valueOf(entry.getValue()));
            }
        }
    }
}

From source file:appium.android.server.http.impl.NettyHttpResponse.java

License:Apache License

public HttpResponse setStatus(int status) {
    response.setStatus(HttpResponseStatus.valueOf(status));
    return this;
}

From source file:co.freeside.betamax.proxy.BetamaxFilters.java

License:Apache License

private DefaultFullHttpResponse playRecordedResponse(Response recordedResponse) throws IOException {
    DefaultFullHttpResponse response;/*from w w w .  j a  v a2s  . c  o  m*/
    HttpResponseStatus status = HttpResponseStatus.valueOf(recordedResponse.getStatus());
    if (recordedResponse.hasBody()) {
        ByteBuf content = getEncodedContent(recordedResponse);
        response = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    } else {
        response = new DefaultFullHttpResponse(HTTP_1_1, status);
    }
    for (Map.Entry<String, String> header : recordedResponse.getHeaders().entrySet()) {
        response.headers().set(header.getKey(), Splitter.onPattern(",\\s*").split(header.getValue()));
    }
    return response;
}

From source file:co.rsk.rpc.netty.Web3ResultHttpResponseHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Web3Result msg) {
    ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(msg.getCode())),
            msg.getContent())).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.bay1ts.bay.core.Response.java

License:Apache License

/**
 * Sets the status code for the//from  w w w .  j  a  v  a  2 s  .  c  o  m
 *
 * @param statusCode the status code
 */
public void status(int statusCode) {
    response.setStatus(HttpResponseStatus.valueOf(statusCode));
}

From source file:com.bay1ts.bay.core.Response.java

License:Apache License

/**
 * Trigger a browser redirect with specific http 3XX status code.
 *
 * @param location       Where to redirect permanently
 * @param httpStatusCode the http status code
 *///  w  w  w . j a v  a2  s  .  co  m
public void redirect(String location, int httpStatusCode) {
    this.isRedirected = true;
    //        if (LOG.isDebugEnabled()) {
    //            LOG.debug("Redirecting ({} to {}", httpStatusCode, location);
    //        }
    //        response.setStatus(httpStatusCode);
    //        response.setHeader("Location", location);
    //        response.setHeader("Connection", "close");
    response.setStatus(HttpResponseStatus.valueOf(httpStatusCode));
    response.headers().set("Location", location);
    response.headers().set("Connection", "close");
    // TODO: 2016/10/12 .?
    //        try {
    //            response.sendError(httpStatusCode);
    //        } catch (IOException e) {
    //            LOG.warn("Exception when trying to redirect permanently", e);
    //        }
}

From source file:com.buildria.mocking.builder.action.StatusCodeAction.java

License:Open Source License

@Nonnull
@Override/*from   w  w  w .  j a  v a2 s  .c om*/
public HttpResponse apply(@Nonnull HttpRequest req, @Nonnull HttpResponse res) {
    Objects.requireNonNull(req);
    Objects.requireNonNull(res);
    res.setStatus(HttpResponseStatus.valueOf(code));
    return res;
}

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }/*from   w  ww .  java 2s .co  m*/

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.chiorichan.http.HttpCode.java

License:Mozilla Public License

public static String msg(int code) {
    switch (code) {
    case HTTP_OK:
        return "OK";
    case HTTP_CONTINUE:
        return "Continue";
    case HTTP_CREATED:
        return "Created";
    case HTTP_ACCEPTED:
        return "Accepted";
    case HTTP_NOT_AUTHORITATIVE:
        return "Non-Authoritative Information";
    case HTTP_NO_CONTENT:
        return "No Content";
    case HTTP_RESET:
        return "Reset Content";
    case HTTP_PARTIAL:
        return "Partial Content";
    case HTTP_MULT_CHOICE:
        return "Multiple Choices";
    case HTTP_MOVED_PERM:
        return "Moved Permanently";
    case HTTP_MOVED_TEMP:
        return "Temporary Redirect";
    case HTTP_SEE_OTHER:
        return "See Other";
    case HTTP_NOT_MODIFIED:
        return "Not Modified";
    case HTTP_USE_PROXY:
        return "Use Proxy";
    case HTTP_TEMPORARY_REDIRECT:
        return "Temporary Redirect";
    case HTTP_BAD_REQUEST:
        return "Bad Request";
    case HTTP_UNAUTHORIZED:
        return "Unauthorized";
    case HTTP_PAYMENT_REQUIRED:
        return "Payment Required";
    case HTTP_FORBIDDEN:
        return "Forbidden";
    case HTTP_NOT_FOUND:
        return "Not Found";
    case HTTP_BAD_METHOD:
        return "Method Not Allowed";
    case HTTP_NOT_ACCEPTABLE:
        return "Not Acceptable";
    case HTTP_PROXY_AUTH:
        return "Proxy Authentication Required";
    case HTTP_CLIENT_TIMEOUT:
        return "Request Time-Out";
    case HTTP_CONFLICT:
        return "Conflict";
    case HTTP_GONE:
        return "Gone";
    case HTTP_LENGTH_REQUIRED:
        return "Length Required";
    case HTTP_PRECON_FAILED:
        return "Precondition Failed";
    case HTTP_ENTITY_TOO_LARGE:
        return "Request Entity Too Large";
    case HTTP_REQ_TOO_LONG:
        return "Request-URI Too Large";
    case HTTP_UNSUPPORTED_TYPE:
        return "Unsupported Media Type";
    case HTTP_TOO_MANY_REQUESTS:
        return "Too Many Requests";
    case HTTP_UNAVAILABLE_FOR_LEGAL_REASONS:
        return "Unavailable for Legal Reasons";
    case HTTP_INTERNAL_ERROR:
        return "Internal Server Error";
    case HTTP_NOT_IMPLEMENTED:
        return "Not Implemented";
    case HTTP_BAD_GATEWAY:
        return "Bad Gateway";
    case HTTP_UNAVAILABLE:
        return "Service Unavailable";
    case HTTP_GATEWAY_TIMEOUT:
        return "Gateway Timeout";
    case HTTP_VERSION:
        return "HTTP Version Not Supported";
    // case HTTP_THE_DOCTOR:
    // return "I'm a Madman With A Blue Box!";
    case HTTP_BLUE_BOX:
        return "Time and Relative Dimensions in Space. Yes, that's it. Names are funny. It's me. I'm the TARDIS.";
    default://  w ww  .  j  a  v  a2s  .c  om
        return HttpResponseStatus.valueOf(code).reasonPhrase().toString();
    }
}

From source file:com.chiorichan.http.HttpHandler.java

License:Mozilla Public License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    try {/* w  ww .  j  av a2 s. com*/
        if (request == null || response == null) {
            NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED
                    + "We got an unexpected exception before the connection was processed:", cause);

            StringBuilder sb = new StringBuilder();
            sb.append("<h1>500 - Internal Server Error</h1>\n");
            sb.append(
                    "<p>The server had encountered an unexpected exception before it could fully process your request, so no extended debug information is or will be available.</p>\n");
            sb.append(
                    "<p>The exception has been logged to the console, so we can only hope the exception is noticed and resolved. We apoligize for any inconvenience.</p>\n");
            sb.append("<p><i>You have a good day now and we will see you again soon. :)</i></p>\n");
            sb.append("<hr>\n");
            sb.append(Versioning.getHTMLFooter());

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.valueOf(500), Unpooled.wrappedBuffer(sb.toString().getBytes()));
            ctx.write(response);

            return;
        }

        String ip = request.getIpAddr();

        if (requestFinished && cause instanceof HttpError) {
            int code = ((HttpError) cause).getHttpCode();

            if (code >= 400 && code <= 499)
                NetworkSecurity.addStrikeToIp(ip, IpStrikeType.HTTP_ERROR_400);
            if (code >= 500 && code <= 599)
                NetworkSecurity.addStrikeToIp(ip, IpStrikeType.HTTP_ERROR_500);

            if (response.getStage() != HttpResponseStage.CLOSED)
                response.sendError((HttpError) cause);
            else
                NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED + " [" + ip
                        + "] For reasons unknown, we caught the HttpError but the connection was already closed.",
                        cause);
            return;
        }

        if (requestFinished && "Connection reset by peer".equals(cause.getMessage())) {
            NetworkManager.getLogger().warning(EnumColor.NEGATIVE + "" + EnumColor.RED + " [" + ip
                    + "] The connection was closed before we could finish the request, if the IP continues to abuse the system it WILL BE BANNED!");
            NetworkSecurity.addStrikeToIp(ip, IpStrikeType.CLOSED_EARLY);
            return;
        }

        ScriptingException evalOrig = null;

        /*
         * Unpackage the EvalFactoryException.
         * Not sure if exceptions from the EvalFactory should be handled differently or not.
         * XXX Maybe skip generating exception pages for errors that were caused internally and report them to Chiori-chan unless the server is in development mode?
         */
        if (cause instanceof ScriptingException && cause.getCause() != null) {
            evalOrig = (ScriptingException) cause;
            cause = cause.getCause();
        }

        /*
         * Presently we can only send one exception to the client
         * So for now we only send the most severe one
         *
         * TODO Enhancement: Make it so each exception is printed out.
         */
        if (cause instanceof MultipleException) {
            IException most = null;

            // The lower the intValue() to more important it became
            for (IException e : ((MultipleException) cause).getExceptions())
                if (e instanceof Throwable
                        && (most == null || most.reportingLevel().intValue() > e.reportingLevel().intValue()))
                    most = e;

            if (most instanceof ScriptingException) {
                evalOrig = (ScriptingException) most;
                cause = most.getCause();
            } else
                cause = (Throwable) most;
        }

        /*
         * TODO Proper Exception Handling. Consider the ability to have these exceptions cached, then delivered by e-mail to chiori-chan and/or server administrator.
         */
        if (cause instanceof HttpError)
            response.sendError((HttpError) cause);
        else if (cause instanceof PermissionDeniedException) {
            PermissionDeniedException pde = (PermissionDeniedException) cause;

            if (pde.getReason() == PermissionDeniedReason.LOGIN_PAGE)
                response.sendLoginPage(pde.getReason().getMessage());
            else
                /*
                 * TODO generate a special permission denied page
                 */
                response.sendError(((PermissionDeniedException) cause).getHttpCode(), cause.getMessage());
        } else if (cause instanceof OutOfMemoryError) {
            log.log(Level.SEVERE,
                    EnumColor.NEGATIVE + "" + EnumColor.RED + "OutOfMemoryError! This is serious!!!");
            response.sendError(500, "We have encountered an internal server error");

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        } else if (evalOrig == null) {
            // Was not caught by EvalFactory
            log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'",
                    EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                    cause.getStackTrace()[0].getFileName(), cause.getStackTrace()[0].getLineNumber(),
                    cause.getMessage());
            response.sendException(cause);

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        } else {
            if (evalOrig.isScriptingException() && !evalOrig.hasScriptTrace()) {
                log.log(Level.WARNING,
                        "We caught an EvalException which was determined to be related to a scripting issue but the exception has no script trace, this might be a combined internal and external problem.",
                        EnumColor.NEGATIVE, EnumColor.RED);
                log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'",
                        EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                        cause.getStackTrace()[0].getFileName(), cause.getStackTrace()[0].getLineNumber(),
                        cause.getMessage());
            } else if (evalOrig.isScriptingException()) {
                ScriptTraceElement element = evalOrig.getScriptTrace()[0];
                log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s:%s, message '%s'",
                        EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                        element.context().filename(), element.getLineNumber(),
                        element.getColumnNumber() > 0 ? element.getColumnNumber() : 0, cause.getMessage());
            } else
                log.log(Level.SEVERE, "%s%sException %s thrown with message '%s'", EnumColor.NEGATIVE,
                        EnumColor.RED, cause.getClass().getName(), cause.getMessage());
            // log.log( Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'", LogColor.NEGATIVE, LogColor.RED, cause.getClass().getName(), cause.getStackTrace()[0].getFileName(),
            // cause.getStackTrace()[0].getLineNumber(), cause.getMessage() );

            response.sendException(evalOrig);

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        }

        finish();
    } catch (Throwable t) {
        NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED
                + "This is an uncaught exception from the exceptionCaught() method:", t);
        // ctx.fireExceptionCaught( t );
    }
}