io.netty.handler.codec.http.HttpResponseStatus # valueOf ( ) 源码实例Demo

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

源代码1 项目: ethsigner   文件: SignerResponse.java

public static SignerResponse<JsonRpcErrorResponse> fromError(final ClientConnectionException e) {
  final String message = e.getMessage();
  final String errorBody = message.substring(message.indexOf(":") + 1).trim();
  final String[] errorParts = errorBody.split(";", 2);
  if (errorParts.length == 2) {
    final String statusCode = errorParts[0];
    final HttpResponseStatus status = HttpResponseStatus.valueOf(Integer.parseInt(statusCode));
    final String jsonBody = errorParts[1];
    JsonRpcErrorResponse jsonRpcResponse = null;
    if (!jsonBody.isEmpty()) {
      jsonRpcResponse = Json.decodeValue(jsonBody, JsonRpcErrorResponse.class);
    }
    return new SignerResponse<>(jsonRpcResponse, status);
  } else {
    throw new RuntimeException("Unable to parse web3j exception message", e);
  }
}
 

/**
 * Returns the {@link HttpResponseStatus} represented by the specified code.
 * If the specified code is a standard RTSP getStatus code, a cached instance
 * will be returned.  Otherwise, a new instance will be returned.
 */
public static HttpResponseStatus valueOf(int code) {
    switch (code) {
    case 250: return LOW_STORAGE_SPACE;
    case 302: return MOVED_TEMPORARILY;
    case 451: return PARAMETER_NOT_UNDERSTOOD;
    case 452: return CONFERENCE_NOT_FOUND;
    case 453: return NOT_ENOUGH_BANDWIDTH;
    case 454: return SESSION_NOT_FOUND;
    case 455: return METHOD_NOT_VALID;
    case 456: return HEADER_FIELD_NOT_VALID;
    case 457: return INVALID_RANGE;
    case 458: return PARAMETER_IS_READONLY;
    case 459: return AGGREGATE_OPERATION_NOT_ALLOWED;
    case 460: return ONLY_AGGREGATE_OPERATION_ALLOWED;
    case 461: return UNSUPPORTED_TRANSPORT;
    case 462: return DESTINATION_UNREACHABLE;
    case 463: return KEY_MANAGEMENT_FAILURE;
    case 505: return RTSP_VERSION_NOT_SUPPORTED;
    case 551: return OPTION_NOT_SUPPORTED;
    default:  return HttpResponseStatus.valueOf(code);
    }
}
 

/**
 * Returns the {@link HttpResponseStatus} represented by the specified code.
 * If the specified code is a standard RTSP getStatus code, a cached instance
 * will be returned.  Otherwise, a new instance will be returned.
 */
public static HttpResponseStatus valueOf(int code) {
    switch (code) {
    case 250: return LOW_STORAGE_SPACE;
    case 302: return MOVED_TEMPORARILY;
    case 451: return PARAMETER_NOT_UNDERSTOOD;
    case 452: return CONFERENCE_NOT_FOUND;
    case 453: return NOT_ENOUGH_BANDWIDTH;
    case 454: return SESSION_NOT_FOUND;
    case 455: return METHOD_NOT_VALID;
    case 456: return HEADER_FIELD_NOT_VALID;
    case 457: return INVALID_RANGE;
    case 458: return PARAMETER_IS_READONLY;
    case 459: return AGGREGATE_OPERATION_NOT_ALLOWED;
    case 460: return ONLY_AGGREGATE_OPERATION_ALLOWED;
    case 461: return UNSUPPORTED_TRANSPORT;
    case 462: return DESTINATION_UNREACHABLE;
    case 463: return KEY_MANAGEMENT_FAILURE;
    case 505: return RTSP_VERSION_NOT_SUPPORTED;
    case 551: return OPTION_NOT_SUPPORTED;
    default:  return HttpResponseStatus.valueOf(code);
    }
}
 
源代码4 项目: msf4j   文件: HttpUtil.java

/**
 * Create a CarbonMessage for a specific status code.
 *
 * @param status HTTP status code
 * @param msg message text
 * @return CarbonMessage representing the status
 */
public static HttpCarbonMessage createTextResponse(int status, String msg) {
    HttpCarbonMessage response = new HttpCarbonMessage(
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status)));
    response.setHttpStatusCode(status);
    if (msg != null) {
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(msg.length()));
        byte[] msgArray = null;
        try {
            msgArray = msg.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to get the byte array from responseValue", e);
        }
        ByteBuffer byteBuffer = ByteBuffer.allocate(msgArray.length);
        byteBuffer.put(msgArray);
        byteBuffer.flip();
        response.addHttpContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(byteBuffer)));
    } else {
        response.setHeader(HttpHeaders.CONTENT_LENGTH, "0");
    }
    return response;
}
 

public HttpClientResponse<ByteBuf> asHttpClientResponse() {
    if (this.networkFailure != null) {
        return null;
    }

    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(status)).when(resp).getStatus();
    Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content))).when(resp).getContent();

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class.getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }

    return resp;
}
 
源代码6 项目: netty4.0.27Learn   文件: SpdyHeaders.java

/**
 * Returns the {@link HttpResponseStatus} represented by the HTTP response status header.
 */
public static HttpResponseStatus getStatus(int spdyVersion, SpdyHeadersFrame frame) {
    try {
        String status = frame.headers().get(HttpNames.STATUS);
        int space = status.indexOf(' ');
        if (space == -1) {
            return HttpResponseStatus.valueOf(Integer.parseInt(status));
        } else {
            int code = Integer.parseInt(status.substring(0, space));
            String reasonPhrase = status.substring(space + 1);
            HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(code);
            if (responseStatus.reasonPhrase().equals(reasonPhrase)) {
                return responseStatus;
            } else {
                return new HttpResponseStatus(code, reasonPhrase);
            }
        }
    } catch (Exception e) {
        return null;
    }
}
 

@Override
  public void messageReceived(ChannelHandlerContext ctx, HttpRequest request) throws Exception {

      if (!request.getDecoderResult().isSuccess()) {
          sendError(ctx, BAD_REQUEST);
          return;
      }

MockHttpServletRequest servletRequest = createServletRequest(request);
      MockHttpServletResponse servletResponse = new MockHttpServletResponse();

this.servlet.service(servletRequest, servletResponse);

      HttpResponseStatus status = HttpResponseStatus.valueOf(servletResponse.getStatus());
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);

for (String name : servletResponse.getHeaderNames()) {
	for (Object value : servletResponse.getHeaderValues(name)) {
		response.addHeader(name, value);
	}
}

      // Write the initial line and the header.
      ctx.write(response);

      InputStream contentStream = new ByteArrayInputStream(servletResponse.getContentAsByteArray());

// Write the content.
      ChannelFuture writeFuture = ctx.write(new ChunkedStream(contentStream));
      writeFuture.addListener(ChannelFutureListener.CLOSE);
  }
 

private void writeErrorResponse(int statusCode, String message, ChannelHandlerContext ctx) {
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
        HttpResponseStatus.valueOf(statusCode),
        Unpooled.copiedBuffer(message, Charset.forName(SentinelConfig.charset())));

    httpResponse.headers().set("Content-Type", "text/plain; charset=" + SentinelConfig.charset());
    ctx.write(httpResponse);

    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
 

public HttpResponse toNettyResponse(LiveHttpResponse httpResponse) {
    io.netty.handler.codec.http.HttpVersion version = toNettyVersion(httpResponse.version());
    HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(httpResponse.status().code());

    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(version, httpResponseStatus, true);

    httpResponse.headers().forEach(httpHeader ->
            nettyResponse.headers().add(httpHeader.name(), httpHeader.value()));

    return nettyResponse;
}
 
源代码10 项目: xyz-hub   文件: XYZHubRESTVerticle.java

private static void failureHandler(RoutingContext context) {
  if (context.failure() != null) {
    sendErrorResponse(context, context.failure());
  } else {
    String message = context.statusCode() == 401 ? "Missing auth credentials." : "A failure occurred during the execution.";
    HttpResponseStatus status = context.statusCode() >= 400 ? HttpResponseStatus.valueOf(context.statusCode()) : INTERNAL_SERVER_ERROR;
    sendErrorResponse(context, new HttpException(status, message));
  }
}
 
源代码11 项目: Dream-Catcher   文件: WhitelistFilter.java

@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (!whitelistEnabled) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // do not allow HTTP CONNECTs to be short-circuited
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        boolean urlWhitelisted = false;

        String url = getFullUrl(httpRequest);

        for (Pattern pattern : whitelistUrls) {
            if (pattern.matcher(url).matches()) {
                urlWhitelisted = true;
                break;
            }
        }

        if (!urlWhitelisted) {
            HttpResponseStatus status = HttpResponseStatus.valueOf(whitelistResponseCode);
            HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
            HttpHeaders.setContentLength(resp, 0L);

            return resp;
        }
    }

    return null;
}
 
源代码12 项目: arcusplatform   文件: HttpSender.java

public void sendError(ChannelHandlerContext ctx, int code, FullHttpRequest req) {
   HttpResponseStatus status = HttpResponseStatus.valueOf(code);
   metrics.incHTTPResponseCounter(className, code);
   FullHttpResponse response = new DefaultFullHttpResponse(
         HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
   response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
源代码13 项目: CapturePacket   文件: WhitelistFilter.java

@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (!whitelistEnabled) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // do not allow HTTP CONNECTs to be short-circuited
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        boolean urlWhitelisted = false;

        String url = getFullUrl(httpRequest);

        for (Pattern pattern : whitelistUrls) {
            if (pattern.matcher(url).matches()) {
                urlWhitelisted = true;
                break;
            }
        }

        if (!urlWhitelisted) {
            HttpResponseStatus status = HttpResponseStatus.valueOf(whitelistResponseCode);
            HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
            HttpHeaders.setContentLength(resp, 0L);

            return resp;
        }
    }

    return null;
}
 

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    Object resMsg = channelHandler.wrote(new NettyChannelContext(nettyChannel), msg);
    if (resMsg instanceof HttpResponseMessage) {
        HttpResponseMessage message = (HttpResponseMessage) resMsg;
        //获取content
        ByteBuf content = Unpooled.copiedBuffer(message.content());
        //获取status
        HttpResponseStatus status = HttpResponseStatus.valueOf(message.getStatus());
        //创建FullHttpResponse对象
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
        //设置header
        message.headers().getAll().forEach((k, v) -> res.headers().set(k, v));
        //设置消息长度
        HttpUtil.setContentLength(res, content.readableBytes());
        //发送
        ChannelFuture f = ctx.writeAndFlush(res);
        if (!message.headers().isKeepAlive()) {
            HttpUtil.setKeepAlive(res, false);
            f.addListener(ChannelFutureListener.CLOSE);
        } else {
            HttpUtil.setKeepAlive(res, true);
        }
    } else {
        super.write(ctx, resMsg, promise);
    }
}
 
源代码15 项目: brpc-java   文件: BrpcHttpObjectDecoder.java

@Override
protected HttpMessage createMessage(String[] initialLine) throws Exception {

    return isDecodingRequest() ? new DefaultHttpRequest(
            HttpVersion.valueOf(initialLine[2]),
            HttpMethod.valueOf(initialLine[0]), initialLine[1], validateHeaders) :
            new DefaultHttpResponse(
                    HttpVersion.valueOf(initialLine[0]),
                    HttpResponseStatus.valueOf(Integer.parseInt(initialLine[1]), initialLine[2]), validateHeaders);
}
 
源代码16 项目: blade   文件: HttpServerHandler.java

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (!ExceptionHandler.isResetByPeer(cause)) {
        log.error(cause.getMessage(), cause);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(500));
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
 
源代码17 项目: multi-model-server   文件: Job.java

public void response(
        byte[] body,
        CharSequence contentType,
        int statusCode,
        String statusPhrase,
        Map<String, String> responseHeaders) {
    HttpResponseStatus status =
            (statusPhrase == null)
                    ? HttpResponseStatus.valueOf(statusCode)
                    : HttpResponseStatus.valueOf(statusCode, statusPhrase);
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);

    if (contentType != null && contentType.length() > 0) {
        resp.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }
    if (responseHeaders != null) {
        for (Map.Entry<String, String> e : responseHeaders.entrySet()) {
            resp.headers().set(e.getKey(), e.getValue());
        }
    }
    resp.content().writeBytes(body);

    /*
     * We can load the models based on the configuration file.Since this Job is
     * not driven by the external connections, we could have a empty context for
     * this job. We shouldn't try to send a response to ctx if this is not triggered
     * by external clients.
     */
    if (ctx != null) {
        NettyUtils.sendHttpResponse(ctx, resp, true);
    }

    logger.debug(
            "Waiting time: {}, Backend time: {}",
            scheduled - begin,
            System.currentTimeMillis() - scheduled);
}
 
源代码18 项目: netty-http2   文件: HttpStreamDecoder.java

private StreamedHttpResponse createHttpResponse(HttpHeadersFrame httpHeadersFrame)
        throws Exception {
    // Create the first line of the request from the name/value pairs
    HttpResponseStatus status = HttpResponseStatus.valueOf(Integer.parseInt(
            httpHeadersFrame.headers().get(":status")));

    httpHeadersFrame.headers().remove(":status");

    StreamedHttpResponse response = new StreamedHttpResponse(HttpVersion.HTTP_1_1, status);
    for (Map.Entry<String, String> e : httpHeadersFrame.headers()) {
        String name = e.getKey();
        String value = e.getValue();
        if (name.charAt(0) != ':') {
            response.headers().add(name, value);
        }
    }

    // Set the Stream-ID as a header
    response.headers().set("X-SPDY-Stream-ID", httpHeadersFrame.getStreamId());

    // The Connection and Keep-Alive headers are no longer valid
    HttpHeaders.setKeepAlive(response, true);

    // Transfer-Encoding header is not valid
    response.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);
    response.headers().remove(HttpHeaders.Names.TRAILER);

    if (httpHeadersFrame.isLast()) {
        response.getContent().close();
        response.setDecoderResult(DecoderResult.SUCCESS);
    } else {
        response.setDecoderResult(DecoderResult.UNFINISHED);
    }

    return response;
}
 
源代码19 项目: zuul   文件: ClientResponseWriter.java

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    int status = 500;
    final String errorMsg = "ClientResponseWriter caught exception in client connection pipeline: " +
            ChannelUtils.channelInfoForLogging(ctx.channel());

    if (cause instanceof ZuulException) {
        final ZuulException ze = (ZuulException) cause;
        status = ze.getStatusCode();
        LOG.error(errorMsg, cause);
    }
    else if (cause instanceof ReadTimeoutException) {
        LOG.error(errorMsg + ", Read timeout fired");
        status = 504;
    }
    else {
        LOG.error(errorMsg, cause);
    }

    if (isHandlingRequest && !startedSendingResponseToClient && ctx.channel().isActive()) {
        final HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(status));
        ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
        startedSendingResponseToClient = true;
    }
    else {
        ctx.close();
    }
}
 

private HttpClientResponse<ByteBuf> getMockResponse(String databaseAccountJson) {
    HttpClientResponse<ByteBuf> resp = Mockito.mock(HttpClientResponse.class);
    Mockito.doReturn(HttpResponseStatus.valueOf(200)).when(resp).getStatus();
    ByteBuf byteBuffer = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, databaseAccountJson);

    Mockito.doReturn(Observable.just(byteBuffer))
            .when(resp).getContent();

    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders = httpHeaders.add(HttpConstants.HttpHeaders.CONTENT_LENGTH, byteBuffer.writerIndex());

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(200), httpHeaders);

    try {
        Constructor<HttpResponseHeaders> constructor = HttpResponseHeaders.class
                .getDeclaredConstructor(HttpResponse.class);
        constructor.setAccessible(true);
        HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse);
        Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders();

    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to instantiate class object.", e);
    }
    return resp;
}