Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#BAD_REQUEST

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#BAD_REQUEST . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestProcessor.java    From mantis with Apache License 2.0 6 votes vote down vote up
public Observable<Void> simulateTimeout(HttpServerRequest<ByteBuf> httpRequest, HttpServerResponse<ByteBuf> response) {
    String uri = httpRequest.getUri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    List<String> timeout = decoder.parameters().get("timeout");
    byte[] contentBytes;
    HttpResponseStatus status = HttpResponseStatus.NO_CONTENT;
    if (null != timeout && !timeout.isEmpty()) {
        try {
            Thread.sleep(Integer.parseInt(timeout.get(0)));
            contentBytes = "".getBytes();
        } catch (Exception e) {
            contentBytes = e.getMessage().getBytes();
            status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        }
    } else {
        status = HttpResponseStatus.BAD_REQUEST;
        contentBytes = "Please provide a timeout parameter.".getBytes();
    }

    response.setStatus(status);
    return response.writeBytesAndFlush(contentBytes);
}
 
Example 2
Source File: HttpDecoder.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private void postBatch(
    final ChannelHandlerContext ctx, final FullHttpRequest in, final List<Object> out
) {
    final Batch batch;
    try (final InputStream inputStream = new ByteBufInputStream(in.content())) {
        batch = mapper.readValue(inputStream, Batch.class);
    } catch (final IOException e) {
        log.error("HTTP Bad Request", e);
        throw new HttpException(HttpResponseStatus.BAD_REQUEST);
    }

    out.add(batch);

    ctx
        .channel()
        .writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK))
        .addListener((ChannelFutureListener) future -> future.channel().close());
}
 
Example 3
Source File: DefaultExceptionHandler.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.error("Exception caught: " + cause);

    HttpResponseStatus status = (cause instanceof BadRequestException) ? HttpResponseStatus.BAD_REQUEST :
             HttpResponseStatus.INTERNAL_SERVER_ERROR;

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    cause.printStackTrace(printWriter);
    String content = stringWriter.toString();

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
            status, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
    response.headers().set(CONTENT_LENGTH,
            response.content().readableBytes());

    ctx.writeAndFlush(response);
    ctx.close();
}
 
Example 4
Source File: NettyHttpServerHandler.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            currentObj.decoderResult().isSuccess() ? HttpResponseStatus.OK : HttpResponseStatus.BAD_REQUEST,
            Unpooled.EMPTY_BUFFER);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
Example 5
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void sendDecodingFailures(ChannelHandlerContext ctx, Throwable t, Object msg) {
	Throwable cause = t.getCause() != null ? t.getCause() : t;

	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Decoding failed: " + msg + " : "), cause);
	}

	ReferenceCountUtil.release(msg);

	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
			cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE:
			                                         HttpResponseStatus.BAD_REQUEST);
	response.headers()
	        .setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
	        .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
	ctx.writeAndFlush(response)
	   .addListener(ChannelFutureListener.CLOSE);
}
 
Example 6
Source File: NoMatchResponseGenerator.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static FullHttpResponse generateNoMatchResponse(RecordedHttpRequest recordedHttpRequest) {
  StringBuilder bodyTextBuilder = new StringBuilder();
  bodyTextBuilder.append("No Matching Request\n").append("Incoming Request Method: ")
      .append(recordedHttpRequest.getMethod()).append("\n").append("Incoming Request URI: ")
      .append(recordedHttpRequest.getUri()).append("\n").append("Incoming Request Headers: ")
      .append(recordedHttpRequest.getHeaders()).append("\n");
  RecordedHttpBody incomingBody = recordedHttpRequest.getHttpBody();
  if (incomingBody != null) {
    if (incomingBody instanceof RecordedEncodedHttpBody) {
      incomingBody = ((RecordedEncodedHttpBody) incomingBody).getDecodedBody();
    }
    if (incomingBody instanceof RecordedStringHttpBody) {
      bodyTextBuilder.append("Incoming Request Body: ").append(((RecordedStringHttpBody) incomingBody).getContent());
    } else {
      bodyTextBuilder.append("Incoming Request Body: (binary content)");
    }
  }
  ByteBuf badRequestBody = Unpooled.wrappedBuffer(bodyTextBuilder.toString().getBytes(Charset.forName("UTF-8")));
  return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, badRequestBody);
}
 
Example 7
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 5 votes vote down vote up
private boolean shouldSendFailureReason(HttpResponseStatus status, RestServiceException exception) {
  if (status == HttpResponseStatus.BAD_REQUEST || exception.shouldIncludeExceptionMessageInResponse()) {
    return true;
  }
  return request != null && request.getArgs().containsKey(RestUtils.InternalKeys.SEND_FAILURE_REASON)
      && (Boolean) request.getArgs().get(RestUtils.InternalKeys.SEND_FAILURE_REASON);
}
 
Example 8
Source File: GraphQLHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus status(final GraphQLResponse response) {

    switch (response.getType()) {
      case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
      case ERROR:
        return HttpResponseStatus.BAD_REQUEST;
      case SUCCESS:
      case NONE:
      default:
        return HttpResponseStatus.OK;
    }
  }
 
Example 9
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus status(final JsonRpcResponse response) {

    switch (response.getType()) {
      case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
      case ERROR:
        return HttpResponseStatus.BAD_REQUEST;
      case SUCCESS:
      case NONE:
      default:
        return HttpResponseStatus.OK;
    }
  }
 
Example 10
Source File: ApplicationInfoValidator.java    From xian with Apache License 2.0 5 votes vote down vote up
public void validate(String name, String value) throws OAuthException {
    if (ApplicationInfo.JSON_STATUS.equals(name)) {
        try {
            Integer.valueOf(value);
        } catch (NumberFormatException e) {
            throw new OAuthException(String.format(ResponseBuilder.ERROR_NOT_INTEGER, ApplicationInfo.JSON_STATUS), HttpResponseStatus.BAD_REQUEST);
        }
    }
}
 
Example 11
Source File: HttpTestServer.java    From crate with Apache License 2.0 5 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest msg) throws UnsupportedEncodingException {
    String uri = msg.uri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    logger.debug("Got Request for " + uri);
    HttpResponseStatus status = fail ? HttpResponseStatus.BAD_REQUEST : HttpResponseStatus.OK;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
            if (entry.getValue().size() == 1) {
                generator.writeStringField(entry.getKey(), URLDecoder.decode(entry.getValue().get(0), "UTF-8"));
            } else {
                generator.writeArrayFieldStart(entry.getKey());
                for (String value : entry.getValue()) {
                    generator.writeString(URLDecoder.decode(value, "UTF-8"));
                }
                generator.writeEndArray();
            }
        }
        generator.writeEndObject();
        generator.close();

    } catch (Exception ex) {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    ByteBuf byteBuf = Unpooled.wrappedBuffer(out.toByteArray());
    responses.add(out.toString(StandardCharsets.UTF_8.name()));

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
    ChannelFuture future = ctx.channel().writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 12
Source File: LProxy.java    From k3pler with GNU General Public License v3.0 5 votes vote down vote up
private HttpResponseStatus getResponseStatus(int ID){
    switch (ID){
        case 0:
            return HttpResponseStatus.BAD_GATEWAY;
        case 1:
            return HttpResponseStatus.BAD_REQUEST;
        case 2:
            return HttpResponseStatus.FORBIDDEN;
        case 3:
            return HttpResponseStatus.NOT_FOUND;
        default:
            return HttpResponseStatus.BAD_GATEWAY;
    }
}
 
Example 13
Source File: InvalidArgumentException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}
 
Example 14
Source File: EthResponseFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public EthSignerResponse ethSigner(final Object id, final JsonRpcError error) {
  return new EthSignerResponse(
      NO_HEADERS, new JsonRpcErrorResponse(id, error), HttpResponseStatus.BAD_REQUEST);
}
 
Example 15
Source File: OAuthUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static FullHttpResponse badRequest() {
   return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
}
 
Example 16
Source File: InvalidSelectorException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}
 
Example 17
Source File: SQLExceptions.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Create a {@link SQLActionException} out of a {@link Throwable}.
 * If concrete {@link ElasticsearchException} is found, first transform it
 * to a {@link CrateException}
 */
public static SQLActionException createSQLActionException(Throwable e, Consumer<Throwable> maskSensitiveInformation) {
    // ideally this method would be a static factory method in SQLActionException,
    // but that would pull too many dependencies for the client

    if (e instanceof SQLActionException) {
        return (SQLActionException) e;
    }
    Throwable unwrappedError = SQLExceptions.unwrap(e);
    e = esToCrateException(unwrappedError);
    try {
        maskSensitiveInformation.accept(e);
    } catch (Exception mpe) {
        e = mpe;
    }

    int errorCode = 5000;
    HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    if (e instanceof CrateException) {
        CrateException crateException = (CrateException) e;
        if (e instanceof ValidationException) {
            errorCode = 4000 + crateException.errorCode();
            httpStatus = HttpResponseStatus.BAD_REQUEST;
        } else if (e instanceof UnauthorizedException) {
            errorCode = 4010 + crateException.errorCode();
            httpStatus = HttpResponseStatus.UNAUTHORIZED;
        } else if (e instanceof ReadOnlyException) {
            errorCode = 4030 + crateException.errorCode();
            httpStatus = HttpResponseStatus.FORBIDDEN;
        } else if (e instanceof ResourceUnknownException) {
            errorCode = 4040 + crateException.errorCode();
            httpStatus = HttpResponseStatus.NOT_FOUND;
        } else if (e instanceof ConflictException) {
            errorCode = 4090 + crateException.errorCode();
            httpStatus = HttpResponseStatus.CONFLICT;
        } else if (e instanceof UnhandledServerException) {
            errorCode = 5000 + crateException.errorCode();
        }
    } else if (e instanceof ParsingException) {
        errorCode = 4000;
        httpStatus = HttpResponseStatus.BAD_REQUEST;
    } else if (e instanceof MapperParsingException) {
        errorCode = 4000;
        httpStatus = HttpResponseStatus.BAD_REQUEST;
    }

    String message = e.getMessage();
    if (message == null) {
        if (e instanceof CrateException && e.getCause() != null) {
            e = e.getCause();   // use cause because it contains a more meaningful error in most cases
        }
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        if (stackTraceElements.length > 0) {
            message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]);
        } else {
            message = "Error in " + e.getClass().getSimpleName();
        }
    } else {
        message = e.getClass().getSimpleName() + ": " + message;
    }

    StackTraceElement[] usefulStacktrace =
        e instanceof MissingPrivilegeException ? e.getStackTrace() : unwrappedError.getStackTrace();
    return new SQLActionException(message, errorCode, httpStatus, usefulStacktrace);
}
 
Example 18
Source File: InvalidElementStateException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}
 
Example 19
Source File: EthResponseFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public EthNodeResponse ethNode(final JsonRpcError error) {
  final JsonRpcErrorResponse errorResponse = new JsonRpcErrorResponse(DEFAULT_ID, error);

  return new EthNodeResponse(
      NO_HEADERS, Json.encode(errorResponse), HttpResponseStatus.BAD_REQUEST);
}
 
Example 20
Source File: EthResponseFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public EthSignerResponse ethSigner(final JsonRpcError error) {
  return new EthSignerResponse(
      NO_HEADERS, new JsonRpcErrorResponse(DEFAULT_ID, error), HttpResponseStatus.BAD_REQUEST);
}