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

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

Introduction

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

Prototype

HttpResponseStatus BAD_GATEWAY

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

Click Source Link

Document

502 Bad Gateway

Usage

From source file:eu.operando.operandoapp.service.ProxyService.java

License:Open Source License

private HttpResponse getPendingResponse() {
    String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>"
            + "Pending Notification" + "</title>\n" + "</head><body>\n"
            + "<h1>The page you are about to visit requires some sensitive information. Please see your pending notifications in Operando to allow or block such requests.</h1>"
            + "</body></html>\n";
    byte[] bytes = body.getBytes(Charset.forName("UTF-8"));
    ByteBuf content = Unpooled.copiedBuffer(bytes);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY,
            content);/*from  www .ja  v a  2  s . c  o m*/
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
    response.headers().set("Content-Type", "text/html; charset=UTF-8");
    response.headers().set("Date", ProxyUtils.formatDate(new Date()));
    response.headers().set(HttpHeaderNames.CONNECTION, "close");
    return response;
}

From source file:eu.operando.operandoapp.service.ProxyService.java

License:Open Source License

private HttpResponse getAwaitingResponse() {
    String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>"
            + "Awaiting Response" + "</title>\n" + "</head><body>\n"
            + "<h1>The page you are about to visit requires some sensitive information. Please see your notification bar to allow or block such requests.</h1>"
            + "</body></html>\n";
    byte[] bytes = body.getBytes(Charset.forName("UTF-8"));
    ByteBuf content = Unpooled.copiedBuffer(bytes);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY,
            content);/*  ww w. j  a va2s  .c o  m*/
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
    response.headers().set("Content-Type", "text/html; charset=UTF-8");
    response.headers().set("Date", ProxyUtils.formatDate(new Date()));
    response.headers().set(HttpHeaderNames.CONNECTION, "close");
    return response;
}

From source file:eu.operando.operandoapp.service.ProxyService.java

License:Open Source License

private HttpResponse getBlockedHostResponse(String hostName) {
    String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>"
            + "Bad Gateway" + "</title>\n" + "</head><body>\n" + "<h1>Host '" + hostName
            + "' is blocked by OperandoApp.</h1>" + "</body></html>\n";
    byte[] bytes = body.getBytes(Charset.forName("UTF-8"));
    ByteBuf content = Unpooled.copiedBuffer(bytes);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY,
            content);/*from ww w.j av  a  2 s . c o  m*/
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
    response.headers().set("Content-Type", "text/html; charset=UTF-8");
    response.headers().set("Date", ProxyUtils.formatDate(new Date()));
    response.headers().set(HttpHeaderNames.CONNECTION, "close");
    return response;
}

From source file:eu.operando.operandoapp.service.ProxyService.java

License:Open Source License

private HttpResponse getUntrustedGatewayResponse() {
    String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>"
            + "Untrusted Gateway" + "</title>\n" + "</head><body>\n"
            + "<h1>Gateway is not included in your trusted list.</h1>" + "<h2>Check Operando settings.</h2>"
            + "</body></html>\n";
    byte[] bytes = body.getBytes(Charset.forName("UTF-8"));
    ByteBuf content = Unpooled.copiedBuffer(bytes);
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY,
            content);/*from  www .  j  a  v a 2  s.c  o m*/
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);
    response.headers().set("Content-Type", "text/html; charset=UTF-8");
    response.headers().set("Date", ProxyUtils.formatDate(new Date()));
    response.headers().set(HttpHeaderNames.CONNECTION, "close");
    return response;
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private boolean possibleRedirect(HttpRequest request, String index, String digest) {
    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.HEAD)
            || (method.equals(HttpMethod.PUT) && HttpUtil.is100ContinueExpected(request))) {
        String redirectAddress;/*w  w  w.  j  ava 2s  . c  om*/
        try {
            redirectAddress = blobService.getRedirectAddress(index, digest);
        } catch (MissingHTTPEndpointException ex) {
            simpleResponse(HttpResponseStatus.BAD_GATEWAY);
            return true;
        }

        if (redirectAddress != null) {
            LOGGER.trace("redirectAddress: {}", redirectAddress);
            sendRedirect(activeScheme + redirectAddress);
            return true;
        }
    }
    return false;
}

From source file:io.nitor.api.backend.proxy.Proxy.java

License:Apache License

public void handle(RoutingContext routingContext) {
    final HttpServerRequest sreq = routingContext.request();
    final boolean isTls = isOrigReqHttps || "https".equals(routingContext.request().scheme());
    final boolean isHTTP2 = routingContext.request().version() == HTTP_2;
    final String chost = getRemoteAddress(routingContext);
    final ProxyTracer tracer = tracerFactory.get();
    String reqId = sreq.headers().get(requestIdHeader);
    boolean hadRequestId = reqId != null;
    if (reqId == null) {
        reqId = Long.toString(requestId.getAndIncrement());
    }//from   w w w .ja v  a 2 s .  c  o m
    tracer.incomingRequestStart(routingContext, isTls, isHTTP2, chost, reqId);
    if (!hadRequestId) {
        sreq.headers().add(requestIdHeader, reqId);
    }

    HttpServerResponse sres = sreq.response();
    sres.exceptionHandler(tracer::outgoingResponseException);
    routingContext.addHeadersEndHandler(tracer::outgoingResponseHeadersEnd);
    sres.bodyEndHandler(tracer::outgoingResponseBodyEnd);
    if (!isHTTP2) {
        sres.headers().add("keep-alive", keepAliveHeaderValue);
        sres.headers().add("connection", "keep-alive");
    }
    sreq.exceptionHandler(t -> {
        tracer.incomingRequestException(t);
        routingContext.fail(new ProxyException(500, RejectReason.incomingRequestFail, t));
    });

    final State state = new State();

    targetResolver.resolveNextHop(routingContext, nextHop -> {
        if (nextHop == null) {
            NullPointerException e = new NullPointerException("nextHop must not be null");
            tracer.incomingRequestException(e);
            throw e;
        }
        tracer.nextHopResolved(nextHop);

        MultiMap sreqh = sreq.headers();
        String origHost = null;
        if (isHTTP2) {
            origHost = sreqh.get(":authority");
        }
        if (origHost == null) {
            origHost = sreqh.get("Host");
        }
        if (origHost == null) {
            ProxyException e = new ProxyException(400, RejectReason.noHostHeader, null);
            tracer.incomingRequestException(e);
            routingContext.fail(e);
            return;
        }
        boolean isWebsocket = !isHTTP2 && "websocket".equals(sreqh.get("upgrade"));
        if (isWebsocket) {
            MultiMap creqh = new CaseInsensitiveHeaders();
            propagateRequestHeaders(isTls, chost, sreqh, origHost, creqh);
            if (nextHop.hostHeader != null) {
                creqh.set("Host", nextHop.hostHeader);
            } else {
                creqh.remove("Host");
            }
            tracer.outgoingWebsocketInitial(creqh);
            client.websocket(nextHop.socketPort, nextHop.socketHost, nextHop.uri, creqh, cws -> {
                // lol no headers copied
                final boolean[] isClosed = { false };
                ServerWebSocket sws = sreq.upgrade();
                tracer.websocketEstablished();
                for (final WebSocketBase[] pair : new WebSocketBase[][] { { sws, cws }, { cws, sws } }) {
                    pair[0].frameHandler(pair[1]::writeFrame).closeHandler(v -> {
                        if (!isClosed[0]) {
                            tracer.establishedWebsocketClosed();
                            isClosed[0] = true;
                            pair[1].close();
                        }
                    }).exceptionHandler(t -> {
                        tracer.establishedWebsocketException(t);
                        t.printStackTrace();
                        if (!isClosed[0]) {
                            isClosed[0] = true;
                            try {
                                pair[1].close();
                            } catch (IllegalStateException e) {
                                // whatever
                            }
                        }
                    });
                }
            }, t -> {
                tracer.outgoingWebsocketException(t);
                t.printStackTrace();
                sres.setStatusCode(HttpResponseStatus.BAD_GATEWAY.code());
                if (t instanceof WebSocketHandshakeRejectedException) {
                    WebSocketHandshakeRejectedException e = (WebSocketHandshakeRejectedException) t;
                    sres.setStatusCode(e.resp.status().code());
                    sres.setStatusMessage(e.resp.status().reasonPhrase());
                    MultiMap cresh = new HeadersAdaptor(e.resp.headers());
                    copyEndToEndHeaders(cresh, sres.headers());
                    sres.headers().add("keep-alive", keepAliveHeaderValue);
                    sres.headers().add("connection", "keep-alive");
                    sres.headers().set("content-length", "0");
                }
                tracer.outgoingResponseInitial();
                tracer.outgoingResponseHeadersEnd(null);
                sres.end();
                tracer.outgoingResponseBodyEnd(null);
            });
            return;
        }
        String expectStr;
        state.expecting100 = null != (expectStr = sreq.headers().get("expect"))
                && expectStr.equalsIgnoreCase("100-continue");
        HttpClientRequest creq = client.request(sreq.method(), nextHop.socketPort, nextHop.socketHost,
                nextHop.uri);
        creq.setTimeout(SECONDS.toMillis(clientReceiveTimeout));
        creq.handler(cres -> {
            cres.exceptionHandler(t -> {
                tracer.incomingResponseException(t);
                if (!state.serverFinished) {
                    state.clientFinished = true;
                    state.serverFinished = true;
                    routingContext.fail(new ProxyException(502, RejectReason.incomingResponseFail, t));
                }
            });
            tracer.incomingResponseStart(cres);
            sres.setStatusCode(cres.statusCode());
            sres.setStatusMessage(cres.statusMessage());
            MultiMap headers = cres.headers();
            copyEndToEndHeaders(headers, sres.headers());
            final boolean reqCompletedBeforeResponse = state.requestComplete;
            if (state.expecting100) {
                log.info("Got " + cres.statusCode() + " instead of 100 Continue");
                if (!isHTTP2) {
                    if (/* state.receivedRequestBodyBefore100 && */ !reqCompletedBeforeResponse) {
                        // TODO investigate whether vertx is able to handle the server request correctly without us closing the conn
                        // but actually the client might have data in transit..
                        log.info(
                                "Client might have started streaming data anyway, so request message boundary is lost. Continue streaming, but close server connection after response complete.");
                        sres.headers().set("connection", "close");
                    } else {
                        log.info(
                                "Client had streamed the complete data anyway. Can carry on without closing server conn.");
                    }
                }
            }
            if (!isHTTP2) {
                if (!sres.headers().contains("connection")
                        || !sres.headers().get("connection").contains("close")) {
                    sres.headers().add("keep-alive", keepAliveHeaderValue);
                    sres.headers().add("connection", "keep-alive");
                }
            }
            if (!headers.contains("content-length")) {
                sres.setChunked(true);
            }
            tracer.outgoingResponseInitial();
            cres.endHandler(v -> {
                tracer.incomingResponseEnd();
                state.clientFinished = true;
                if (!state.serverFinished) {
                    state.serverFinished = true;
                    sres.end();
                }
                if (state.expecting100
                        && /* state.receivedRequestBodyBefore100 && */ !reqCompletedBeforeResponse) {
                    log.info(
                            "Client had started streaming data anyway, so request message boundary is lost. Close client connection.");
                    creq.connection().close();
                }
            });
            pump.start(cres, sres, tracer);
        });
        creq.exceptionHandler(t -> {
            tracer.outgoingRequestException(t);
            if (!state.serverFinished) {
                state.clientFinished = true;
                state.serverFinished = true;
                routingContext.fail(new ProxyException(502, RejectReason.outgoingRequestFail, t));
            }
        });
        MultiMap creqh = creq.headers();
        propagateRequestHeaders(isTls, chost, sreqh, origHost, creqh);
        creq.headers().addAll(addHeaders);
        if (nextHop.hostHeader != null) {
            creq.setHost(nextHop.hostHeader);
        } else {
            creqh.remove("host");
        }
        if (sreqh.getAll("transfer-encoding").stream().anyMatch(v -> v.equals("chunked"))) {
            creq.setChunked(true);
        }
        sres.closeHandler(v -> {
            if (!state.clientFinished) {
                state.clientFinished = true;
                tracer.incomingConnectionPrematurelyClosed();
                HttpConnection connection = creq.connection();
                if (connection != null) {
                    connection.close();
                } // else TODO
            }
            if (!state.serverFinished) {
                state.serverFinished = true;
                routingContext.fail(new ProxyException(0, RejectReason.outgoingResponseFail, null));
            }
        });
        tracer.outgoingRequestInitial(creq);
        if (sreq.isEnded()) {
            state.requestComplete = true;
            Buffer body = routingContext.getBody();
            if (body == null || body.length() == 0) {
                creq.end();
            } else {
                if (!creq.isChunked()) {
                    creq.putHeader("content-length", Integer.toString(body.length()));
                }
                creq.end(routingContext.getBody());
            }
            tracer.incomingRequestEnd();
        } else {
            sreq.endHandler(v -> {
                state.requestComplete = true;
                try {
                    creq.end();
                } catch (IllegalStateException ex) {
                    // ignore - nothing can be done - the request is already complete/closed - TODO log?
                }
                tracer.incomingRequestEnd();
            });

            ReadStream<Buffer> sreqStream;
            if (state.expecting100) {
                log.debug("Expect: 100");
                creq.continueHandler(v -> {
                    // no longer expecting 100, it's like a normal not-expecting-100 request from now on
                    state.expecting100 = false;
                    // since we received 100 Continue, we know the server agrees to accept all the request body, so we can assume we are forgiven for sending data early
                    state.receivedRequestBodyBefore100 = false;
                    log.info("Got 100, propagating");
                    sres.writeContinue();
                });
                // in this case we must flush request headers before the body is sent
                creq.sendHead();
                sreqStream = new ReadStreamWrapper<Buffer>(sreq) {
                    final LazyHandlerWrapper<Buffer> handlerWrapper = new LazyHandlerWrapper<Buffer>(
                            super::handler, null) {
                        @Override
                        public void handle(Buffer event) {
                            log.info("Got first request body chunk");
                            if (state.expecting100) {
                                log.info("Got request body before '100 Continue'");
                                // data received despite not having yet recived 100-continue
                                state.receivedRequestBodyBefore100 = true;
                            }
                            deactivate();
                            wrapped.handle(event);
                        }
                    };

                    @Override
                    public ReadStream<Buffer> handler(Handler<Buffer> handler) {
                        return handlerWrapper.handler(handler, this);
                    }
                };
            } else {
                log.debug("Not expect-100");
                sreqStream = sreq;
            }
            pump.start(sreqStream, creq, tracer);
        }
    });
}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private void onComplete(final ChannelHandlerContext ctx, final int index) {
    log.info("onComplete: {}", index);

    completedSet.set(index);/*from  w  ww .j  a  va  2s.com*/

    mds.flagStored(ctx.executor(), storageNodes.get(index).getId(), etag);

    if (completedSet.cardinality() != outboundCount)
        return;

    log.info("all onComplete");

    final String md5;
    final long size;

    if (fon.isPresent()) {
        md5 = fon.get().attributes.md5;
        size = fon.get().attributes.size;

        digestFinal();
    } else {
        // todo: for mln copy md5 and size from original object
        md5 = digestFinal();
        log.info("md5: ", md5);

        size = receivedSize.longValue();
        receivedSize.set(0);
        log.info("size: {}", size);
    }

    ExtendedObjectAttributes eoa = new ExtendedObjectAttributes(false, size, md5, etag.value,
            completedSet.cardinality(), System.currentTimeMillis());
    final FullObjectRequest req = new FullObjectRequest(objectRequest, eoa);

    log.info("mds.put: {}", req);

    mds.put(ctx.executor(), req).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            HttpResponseStatus status = future.isSuccess() ? HttpResponseStatus.OK
                    : HttpResponseStatus.BAD_GATEWAY;

            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
            log.info("writing back to client: {}", response);
            ctx.writeAndFlush(response).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info("write back successful. closing channel");
                    ctx.channel().close();
                }
            });
        }
    });
}

From source file:org.iotivity.cloud.base.protocols.http.HCProxyProcessor.java

License:Open Source License

private HttpResponseStatus getHttpResponseStatus(ResponseStatus coapResponseStatus, boolean isPayload) {

    HttpResponseStatus httpStatusCode = HttpResponseStatus.NOT_IMPLEMENTED;

    if (coapResponseStatus == ResponseStatus.CREATED) {

        httpStatusCode = HttpResponseStatus.CREATED;

    } else if (coapResponseStatus == ResponseStatus.DELETED || coapResponseStatus == ResponseStatus.CHANGED
            || coapResponseStatus == ResponseStatus.CONTENT) {

        if (isPayload) {
            httpStatusCode = HttpResponseStatus.OK;
        } else {//from  w w w.ja v  a 2  s  .c o  m
            httpStatusCode = HttpResponseStatus.NO_CONTENT;
        }

    } else if (coapResponseStatus == ResponseStatus.VALID) {

        if (isPayload) {
            httpStatusCode = HttpResponseStatus.OK;
        } else {
            httpStatusCode = HttpResponseStatus.NOT_MODIFIED;
        }

    } else if (coapResponseStatus == ResponseStatus.UNAUTHORIZED
            || coapResponseStatus == ResponseStatus.FORBIDDEN) {

        httpStatusCode = HttpResponseStatus.FORBIDDEN;

    } else if (coapResponseStatus == ResponseStatus.BAD_REQUEST
            || coapResponseStatus == ResponseStatus.BAD_OPTION) {

        httpStatusCode = HttpResponseStatus.BAD_REQUEST;

    } else if (coapResponseStatus == ResponseStatus.METHOD_NOT_ALLOWED) {

        // The HC Proxy should return a HTTP reason-phrase
        // in the HTTP status line that starts with the string
        // "CoAP server returned 4.05"
        // in order to facilitate troubleshooting.
        httpStatusCode = new HttpResponseStatus(400, "CoAP server returned 4.05");

    } else if (coapResponseStatus == ResponseStatus.NOT_ACCEPTABLE) {

        httpStatusCode = HttpResponseStatus.NOT_ACCEPTABLE;

    } else if (coapResponseStatus == ResponseStatus.PRECONDITION_FAILED) {

        httpStatusCode = HttpResponseStatus.PRECONDITION_FAILED;

    } else if (coapResponseStatus == ResponseStatus.UNSUPPORTED_CONTENT_FORMAT) {

        httpStatusCode = HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;

    } else if (coapResponseStatus == ResponseStatus.BAD_GATEWAY
            || coapResponseStatus == ResponseStatus.PROXY_NOT_SUPPORTED) {

        httpStatusCode = HttpResponseStatus.BAD_GATEWAY;

    } else if (coapResponseStatus == ResponseStatus.SERVICE_UNAVAILABLE) {

        httpStatusCode = HttpResponseStatus.SERVICE_UNAVAILABLE;

    } else if (coapResponseStatus == ResponseStatus.GATEWAY_TIMEOUT) {

        httpStatusCode = HttpResponseStatus.GATEWAY_TIMEOUT;

    } else if (coapResponseStatus == ResponseStatus.NOT_FOUND) {

        httpStatusCode = HttpResponseStatus.NOT_FOUND;

    } else if (coapResponseStatus == ResponseStatus.INTERNAL_SERVER_ERROR) {

        httpStatusCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }

    return httpStatusCode;
}

From source file:org.jspare.forvertx.web.handling.Handling.java

License:Apache License

/**
 * Bad gateway.
 */
public void badGateway() {

    status(HttpResponseStatus.BAD_GATEWAY);
    end();
}

From source file:org.jspare.forvertx.web.handling.Handling.java

License:Apache License

/**
 * Bad gateway.//from  w w  w  .  java  2 s .c o  m
 *
 * @param content the content
 */
public void badGateway(String content) {

    status(HttpResponseStatus.BAD_GATEWAY);
    res.setChunked(true);
    res.write(content, StandardCharsets.UTF_8.name());
    end();
}