Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#valueOf()

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#valueOf() . These examples are extracted from open source projects. 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 Project: ethsigner   File: SignerResponse.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 2
/**
 * 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);
    }
}
 
Example 3
/**
 * 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);
    }
}
 
Example 4
Source Project: msf4j   File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
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;
}
 
Example 6
Source Project: netty4.0.27Learn   File: SpdyHeaders.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 7
@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);
  }
 
Example 8
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);
}
 
Example 9
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;
}
 
Example 10
Source Project: xyz-hub   File: XYZHubRESTVerticle.java    License: Apache License 2.0 5 votes vote down vote up
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));
  }
}
 
Example 11
Source Project: Dream-Catcher   File: WhitelistFilter.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 12
Source Project: arcusplatform   File: HttpSender.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 13
Source Project: CapturePacket   File: WhitelistFilter.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 14
@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);
    }
}
 
Example 15
Source Project: brpc-java   File: BrpcHttpObjectDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 16
Source Project: blade   File: HttpServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 17
Source Project: multi-model-server   File: Job.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 18
Source Project: netty-http2   File: HttpStreamDecoder.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 19
Source Project: zuul   File: ClientResponseWriter.java    License: Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 20
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;
}