io.netty.handler.codec.http.HttpResponseStatus # BAD_REQUEST 源码实例Demo

下面列出了 io.netty.handler.codec.http.HttpResponseStatus # BAD_REQUEST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: mantis   文件: RequestProcessor.java

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);
}
 
源代码2 项目: ffwd   文件: HttpDecoder.java

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());
}
 

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);
}
 

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);
}
 
源代码5 项目: pulsar   文件: NettyHttpServerHandler.java

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;
}
 

@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();
}
 
源代码7 项目: besu   文件: GraphQLHttpService.java

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;
    }
  }
 
源代码8 项目: besu   文件: JsonRpcHttpService.java

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;
    }
  }
 
源代码9 项目: crate   文件: HttpTestServer.java

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);
}
 
源代码10 项目: k3pler   文件: LProxy.java

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;
    }
}
 
源代码11 项目: xian   文件: ApplicationInfoValidator.java

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);
        }
    }
}
 
源代码12 项目: ambry   文件: NettyResponseChannel.java

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);
}
 
源代码13 项目: ethsigner   文件: EthResponseFactory.java

public EthSignerResponse ethSigner(final Object id, final JsonRpcError error) {
  return new EthSignerResponse(
      NO_HEADERS, new JsonRpcErrorResponse(id, error), HttpResponseStatus.BAD_REQUEST);
}
 
源代码14 项目: ethsigner   文件: EthResponseFactory.java

public EthSignerResponse ethSigner(final JsonRpcError error) {
  return new EthSignerResponse(
      NO_HEADERS, new JsonRpcErrorResponse(DEFAULT_ID, error), HttpResponseStatus.BAD_REQUEST);
}
 
源代码15 项目: ethsigner   文件: EthResponseFactory.java

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);
}
 

@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}
 
源代码17 项目: crate   文件: SQLExceptions.java

/**
 * 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);
}
 

@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}
 
源代码19 项目: arcusplatform   文件: OAuthUtil.java

public static FullHttpResponse badRequest() {
   return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
}
 

@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.BAD_REQUEST;
}