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

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

Introduction

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

Prototype

HttpResponseStatus BAD_REQUEST

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

Click Source Link

Document

400 Bad Request

Usage

From source file:co.cask.cdap.guides.BackLinksHandler.java

License:Apache License

@Path("backlink")
@POST//from   w  ww .  j  a  v  a 2  s  . c  om
public void handleBackLink(HttpServiceRequest request, HttpServiceResponder responder) {

    ByteBuffer requestContents = request.getContent();

    if (requestContents == null) {
        responder.sendError(HttpResponseStatus.NO_CONTENT.code(), "Request content is empty.");
        return;
    }

    if (parseAndStore(Charsets.UTF_8.decode(requestContents).toString().trim())) {
        responder.sendStatus(HttpResponseStatus.OK.code());
    } else {
        responder.sendError(HttpResponseStatus.BAD_REQUEST.code(), "Malformed backlink information");
    }
}

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

License:Apache License

protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;//from  www  .  j  a  v a2s.com
    }
    QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri());
    String target = urlDecoder.path();
    if (request.getMethod() == HttpMethod.POST) {
        log.trace("POST Method handling triggered for {}", request);
        String postBody = request.content().toString(CharsetUtil.UTF_8);
        log.trace("POST body {}", postBody);
        urlDecoder = new QueryStringDecoder(postBody, false);
    }
    log.trace("target uri {}", target);
    KVPairs kv = new KVPairs();
    /**
     * The "/query/google/submit" endpoint needs to unpack the
     * "state" parameter into KV pairs.
     */
    if (target.equals("/query/google/submit")) {
        String state = urlDecoder.parameters().get("state").get(0);
        QueryStringDecoder newDecoder = new QueryStringDecoder(state, false);
        decodeParameters(newDecoder, kv);
        if (urlDecoder.parameters().containsKey("code")) {
            kv.add(GoogleDriveAuthentication.authtoken, urlDecoder.parameters().get("code").get(0));
        }
        if (urlDecoder.parameters().containsKey("error")) {
            kv.add(GoogleDriveAuthentication.autherror, urlDecoder.parameters().get("error").get(0));
        }
    } else {
        decodeParameters(urlDecoder, kv);
    }
    log.trace("kv pairs {}", kv);
    switch (target) {
    case "/":
        sendRedirect(ctx, "/query/index.html");
        break;
    case "/q/":
        sendRedirect(ctx, "/query/call?" + kv.toString());
        break;
    case "/query/call":
    case "/query/call/":
        QueryServer.rawQueryCalls.inc();
        queryQueue.queueQuery(meshQueryMaster, kv, request, ctx);
        break;
    case "/query/google/authorization":
        GoogleDriveAuthentication.gdriveAuthorization(kv, ctx);
        break;
    case "/query/google/submit":
        boolean success = GoogleDriveAuthentication.gdriveAccessToken(kv, ctx);
        if (success) {
            queryQueue.queueQuery(meshQueryMaster, kv, request, ctx);
        }
        break;
    default:
        fastHandle(ctx, request, target, kv);
        break;
    }
}

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrashTest.java

License:Apache License

@Ignore
@Test//w  ww.ja  va 2  s  . c om
public void checkServerReceivesPostedData() throws Exception {
    String expectedReportId = "deadcafe";
    Map<String, String> attributes = new ConcurrentHashMap<>();

    myTestServer.setResponseSupplier(httpRequest -> {
        if (httpRequest.method() != HttpMethod.POST) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        }

        HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest);
        try {
            for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) {
                if (httpData instanceof Attribute) {
                    Attribute attr = (Attribute) httpData;
                    attributes.put(attr.getName(), attr.getValue());
                }
            }
        } catch (IOException e) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        } finally {
            requestDecoder.destroy();
        }

        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8)));
    });

    CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException)
            .setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
    CompletableFuture<String> reportId = myReporter.submit(report);

    assertEquals(expectedReportId, reportId.get());

    // assert that the server get the expected data
    assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID));
    assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION));

    // Note: the exception message should have been elided
    assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE,
            attributes.get(GoogleCrash.KEY_EXCEPTION_INFO));

    List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02");
    report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct")
            .setVersion("1.2.3.4").build();

    attributes.clear();

    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());

    // check that the crash count and descriptions made through
    assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes")));
    assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc"));

    Path testData = Paths.get(AndroidTestBase.getTestDataPath());
    List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8);
    report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build();

    attributes.clear();

    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());
    assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt"));
}

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrashTest.java

License:Apache License

@Test(expected = ExecutionException.class)
public void checkServerErrorCaptured() throws Exception {
    myTestServer.setResponseSupplier(/*from  ww w .j a  va2  s  .c  om*/
            httpRequest -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
    CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException)
            .setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
    myReporter.submit(report).get();
    fail("The above get call should have failed");
}

From source file:com.barchart.netty.rest.client.transport.TestURLConnectionTransport.java

License:BSD License

@Before
public void setUp() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();/*from w ww.j ava  2s.  c  om*/
    s.close();

    final HttpServer server = Servers.createHttpServer().requestHandler("/test", new RequestHandlerBase() {
        @Override
        public void handle(final HttpServerRequest request) throws IOException {

            if (request.getMethod() == HttpMethod.POST) {
                request.response().setStatus(HttpResponseStatus.OK);
            } else {
                request.response().setStatus(HttpResponseStatus.BAD_REQUEST);
            }
            request.response().write(request.getMethod().name());
            request.response().finish();

        }
    });

    server.listen(port, "localhost").sync();

}

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

License:BSD License

/**
 * Verify that the specified parameters are provided in the request. If they
 * are missing, send an error response./*  w w  w  . ja v  a2  s. c om*/
 *
 * @param params The list of required parameters
 * @return True if parameters exist, false if an error response was sent
 */
protected static boolean requireParams(final HttpServerRequest request, final String... params) {

    for (final String param : params) {
        final String value = request.getParameter(param);
        if (value == null || value.isEmpty()) {
            complete(request.response(), HttpResponseStatus.BAD_REQUEST, param + " is invalid or not provided");
            return false;
        }
    }

    return true;

}

From source file:com.beeswax.hexbid.handler.BidHandler.java

License:Apache License

/**
 * //ww w . j  ava 2s  .c  o  m
 * Process full bid request with following error codes:</br>
 * </br>
 * 200 if it sets bid price in {@link BidAgentResponse} successfully.</br>
 * 204 if no bid is made for this request</br>
 * 400 if there is a parsing error {@link BidAgentRequest} or it fails to get bidding strategy.</br>
 * 500 if server experienced an error.</br>
 * 
 * @param ChannelHandlerContext
 * 
 * @return FullHttpResponse
 * 
 */
public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    LOGGER.debug("/bid request");

    try {
        final BidAgentRequest bidRequest = (BidAgentRequest) BidProtobufParser
                .parseProtoBytebuf(request.content(), BidAgentRequest.newBuilder());
        final Optional<BidAgentResponse> bidResponse = bidder.SetBid(bidRequest);

        if (!bidResponse.isPresent()) {
            LOGGER.debug("No Bid");
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        }

        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, Unpooled.wrappedBuffer(bidResponse.get().toByteArray()));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, new AsciiString("application/x-protobuf"));
        return response;

    } catch (InvalidProtocolBufferException | IllegalArgumentException e) {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                Unpooled.wrappedBuffer("Bad request".getBytes()));
    } catch (Exception e) {
        LOGGER.error("Unexpected error when setting bid", e);
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                Unpooled.wrappedBuffer("Internal error when setting bid".getBytes()));
    }
}

From source file:com.beeswax.hexbid.handler.BidHandlerTest.java

License:Apache License

@Test
public void processRequestTest_InvalidProto() {
    final FullHttpRequest request = Mockito.mock(FullHttpRequest.class);
    Mockito.when(request.content()).thenReturn(Unpooled.wrappedBuffer("Invalid proto".getBytes()));

    final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    final BidHandler handler = new BidHandler();
    final FullHttpResponse response = handler.processRequest(ctx, request);
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST, response.status());
    Assert.assertEquals("Bad request", response.content().toString(Charset.forName("UTF-8")));
}

From source file:com.beeswax.http.handler.GlobalHandler.java

License:Apache License

@Override
public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) {
    try {//from ww  w .ja v  a2  s.  c om
        LOGGER.error("Exception occurred. Returning empty `500` response", cause);
        final FullHttpResponse errResponse;
        if (cause instanceof IllegalArgumentException) {
            errResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        } else {
            errResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }

        errResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, errResponse.content().readableBytes());
        ctx.writeAndFlush(errResponse);
    } catch (Throwable t) {
        LOGGER.error("Error occured when returning empty `500` response", t);
    }
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error.//from  www  .j a  v a 2  s  .c om
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
    HttpResponseStatus status;
    StringBuilder errReason = new StringBuilder();
    if (cause instanceof RestServiceException) {
        RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode();
        errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
        status = getHttpResponseStatus(errorResponseStatus);
        if (status == HttpResponseStatus.BAD_REQUEST) {
            errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]");
        }
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        errorResponseStatus = ResponseStatus.InternalServerError;
    }
    String fullMsg = "Failure: " + status + errReason;
    logger.trace("Constructed error response for the client - [{}]", fullMsg);
    FullHttpResponse response;
    if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.wrappedBuffer(fullMsg.getBytes()));
    } else {
        // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET.
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4)
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    }
    HttpHeaders.setDate(response, new GregorianCalendar().getTime());
    HttpHeaders.setContentLength(response, fullMsg.length());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    boolean keepAlive = !forceClose && HttpHeaders.isKeepAlive(responseMetadata) && request != null
            && !request.getRestMethod().equals(RestMethod.POST)
            && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status);
    HttpHeaders.setKeepAlive(response, keepAlive);
    return response;
}