Java Code Examples for io.netty.handler.codec.http.HttpMethod#equals()

The following examples show how to use io.netty.handler.codec.http.HttpMethod#equals() . 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: EndpointMetricsHandlerDefaultImpl.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Timer requestTimer(HttpMethod m) {
    if (m == null) {
        return otherRequests;
    }
    else {
        if (m.equals(HttpMethod.GET))
            return getRequests;
        else if (m.equals(HttpMethod.POST))
            return postRequests;
        else if (m.equals(HttpMethod.PUT))
            return putRequests;
        else if (m.equals(HttpMethod.DELETE))
            return deleteRequests;
        else
            return otherRequests;
    }
}
 
Example 2
Source File: EndpointMetricsHandlerDefaultImplTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Timer expectedRequestTimer(HttpMethod m, EndpointMetricsHandlerDefaultImpl impl) {
    if (m == null) {
        return impl.otherRequests;
    }
    else {
        if (m.equals(HttpMethod.GET))
            return impl.getRequests;
        else if (m.equals(HttpMethod.POST))
            return impl.postRequests;
        else if (m.equals(HttpMethod.PUT))
            return impl.putRequests;
        else if (m.equals(HttpMethod.DELETE))
            return impl.deleteRequests;
        else
            return impl.otherRequests;
    }
}
 
Example 3
Source File: BaseAction.java    From nettice with Apache License 2.0 6 votes vote down vote up
/**
 * 获取请求参数 Map
 */
private Map<String, List<String>> getParamMap(){
	Map<String, List<String>> paramMap = new HashMap<String, List<String>>();
	
	Object msg = DataHolder.getRequest();
	HttpRequest request = (HttpRequest) msg;
	HttpMethod method = request.method();
	if(method.equals(HttpMethod.GET)){
		String uri = request.uri();
		QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charset.forName(CharEncoding.UTF_8));
		paramMap = queryDecoder.parameters();
		
	}else if(method.equals(HttpMethod.POST)){
		FullHttpRequest fullRequest = (FullHttpRequest) msg;
		paramMap = getPostParamMap(fullRequest);
	}
	
	return paramMap;
}
 
Example 4
Source File: RouteMatcher.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public void handle(RakamHttpRequest request)
{
    String path = cleanPath(request.path());
    int lastIndex = path.length() - 1;
    if (lastIndex > 0 && path.charAt(lastIndex) == '/') {
        path = path.substring(0, lastIndex);
    }

    HttpMethod method = request.getMethod();
    final HttpRequestHandler handler = routes.get(new PatternBinding(method, path));
    if (handler != null) {
        if (handler instanceof WebSocketService) {
            request.context().attr(PATH).set(path);
        }
        handler.handle(request);
    }
    else {
        for (Map.Entry<PatternBinding, HttpRequestHandler> prefixRoute : prefixRoutes) {
            if (method.equals(prefixRoute.getKey().method) && path.startsWith(prefixRoute.getKey().pattern)) {
                prefixRoute.getValue().handle(request);
                return;
            }
        }
        noMatch.handle(request);
    }
}
 
Example 5
Source File: ThriftMarshaller.java    From xio with Apache License 2.0 6 votes vote down vote up
private Http1Method build(HttpMethod method) {
  if (method != null) {
    if (method.equals(HttpMethod.CONNECT)) {
      return Http1Method.CONNECT;
    } else if (method.equals(HttpMethod.DELETE)) {
      return Http1Method.DELETE;
    } else if (method.equals(HttpMethod.GET)) {
      return Http1Method.GET;
    } else if (method.equals(HttpMethod.HEAD)) {
      return Http1Method.HEAD;
    } else if (method.equals(HttpMethod.OPTIONS)) {
      return Http1Method.OPTIONS;
    } else if (method.equals(HttpMethod.PATCH)) {
      return Http1Method.PATCH;
    } else if (method.equals(HttpMethod.POST)) {
      return Http1Method.POST;
    } else if (method.equals(HttpMethod.PUT)) {
      return Http1Method.PUT;
    } else if (method.equals(HttpMethod.TRACE)) {
      return Http1Method.TRACE;
    }
  }
  return null;
}
 
Example 6
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private boolean possibleRedirect(HttpRequest request, String index, String digest) {
    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET) ||
        method.equals(HttpMethod.HEAD) ||
        (method.equals(HttpMethod.PUT) &&
         HttpUtil.is100ContinueExpected(request))) {
        String redirectAddress;
        try {
            redirectAddress = blobService.getRedirectAddress(index, digest);
        } catch (MissingHTTPEndpointException ex) {
            simpleResponse(request, HttpResponseStatus.BAD_GATEWAY);
            return true;
        }

        if (redirectAddress != null) {
            LOGGER.trace("redirectAddress: {}", redirectAddress);
            sendRedirect(request, activeScheme + redirectAddress);
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: HttpBlobHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
private void handleBlobRequest(HttpRequest request, @Nullable HttpContent content) throws IOException {
    if (possibleRedirect(request, index, digest)) {
        return;
    }

    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET)) {
        get(request, index, digest);
        reset();
    } else if (method.equals(HttpMethod.HEAD)) {
        head(request, index, digest);
    } else if (method.equals(HttpMethod.PUT)) {
        put(request, content, index, digest);
    } else if (method.equals(HttpMethod.DELETE)) {
        delete(request, index, digest);
    } else {
        simpleResponse(request, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
}
 
Example 8
Source File: AbstractRouteMapper.java    From api-gateway-core with Apache License 2.0 5 votes vote down vote up
/**
 * 遍历所有的路由,返回符合请求的路由
 * @param path
 * @param method
 * @return
 */
@Override
public Route getRoute(String path, HttpMethod method) {
    for (Route route : getRouteList()) {
        if (!method.equals(route.getMethod())) {
            continue;
        }
        if (route.getPath().equals(path)) {
            route = route.clone();
            return route;
        }
        if (this.pathMatcher.match(route.getPath(), path)) {
            route = route.clone();
            Map<String, String> uriTemplateVariables = this.pathMatcher.extractUriTemplateVariables(route.getPath(), path);
            if (!uriTemplateVariables.isEmpty()) {
                String mapUrl = route.getMapUrl().toString();
                for (Map.Entry<String, String> entry : uriTemplateVariables.entrySet()) {
                    mapUrl = mapUrl.replaceAll(String.format("\\{%s}", entry.getKey()), entry.getValue());
                }
                try {
                    route.setMapUrl(new URL(mapUrl));
                } catch (MalformedURLException e) {
                    logger.error(e.getMessage());
                }
            }

            return route;
        }
    }
    return null;
}
 
Example 9
Source File: HttpThriftBufDecoder.java    From nettythrift with Apache License 2.0 5 votes vote down vote up
private boolean directHandleMethod(ChannelHandlerContext ctx, FullHttpRequest request, HttpMethod method) {
	if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.POST)) {
		return false;
	}
	// 处理 OPTIONS 请求
	HttpResponseStatus status = HttpResponseStatus.OK;
	boolean invalid = false;
	if (!method.equals(HttpMethod.OPTIONS)) {
		invalid = true;
		status = HttpResponseStatus.METHOD_NOT_ALLOWED;
	}
	DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.EMPTY_BUFFER);
	HttpHeaders headers = response.headers();
	// headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS,
	// "X-Requested-With, accept, origin, content-type");
	headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "X-Requested-With, content-type");
	headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS");
	headers.set(HttpHeaderNames.SERVER, "Netty5");
	if (invalid) {
		headers.set("Client-Warning", "Invalid Method");
	}
	boolean keepAlive = HttpHeaderUtil.isKeepAlive(request);
	if (keepAlive) {
		response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
	}
	ctx.write(response);
	ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
	if (!keepAlive) {
		future.addListener(ChannelFutureListener.CLOSE);
	}
	return true;
}
 
Example 10
Source File: HttpServerHandler.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final FullHttpRequest request) {
    String requestPath = request.uri();
    String requestBody = request.content().toString(CharsetUtil.UTF_8);
    HttpMethod method = request.method();
    if (!URL_PATTERN.matcher(requestPath).matches()) {
        response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
                channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    if ("/scaling/job/start".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
        startJob(channelHandlerContext, requestBody);
        return;
    }
    if (requestPath.contains("/scaling/job/progress/") && method.equals(HttpMethod.GET)) {
        getJobProgress(channelHandlerContext, requestPath);
        return;
    }
    if ("/scaling/job/list".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.GET)) {
        listAllJobs(channelHandlerContext);
        return;
    }
    if ("/scaling/job/stop".equalsIgnoreCase(requestPath) && method.equals(HttpMethod.POST)) {
        stopJob(channelHandlerContext, requestBody);
        return;
    }
    response(GSON.toJson(ResponseContentUtil.handleBadRequest("Not support request!")),
            channelHandlerContext, HttpResponseStatus.BAD_REQUEST);
}
 
Example 11
Source File: HttpAcceptorHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
   FullHttpRequest request = (FullHttpRequest) msg;
   HttpMethod method = request.method();
   // if we are a post then we send upstream, otherwise we are just being prompted for a response.
   if (method.equals(HttpMethod.POST)) {
      ctx.fireChannelRead(ReferenceCountUtil.retain(((FullHttpRequest) msg).content()));
      // add a new response
      responses.put(new ResponseHolder(System.currentTimeMillis() + responseTime, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
      ReferenceCountUtil.release(msg);
      return;
   }
   super.channelRead(ctx, msg);
}
 
Example 12
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Does the keep-alive test by setting the {@link HttpHeaderNames#CONNECTION} to its two possible values and tests
 * that the response has the appropriate value for the {@link HttpHeaderNames#CONNECTION}.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpMethod the {@link HttpMethod} of the request.
 * @param errorCode the {@link RestServiceErrorCode} to induce at {@link MockNettyMessageProcessor}. {@code null} if
 *                  {@link TestingUri#OnResponseCompleteWithNonRestException} is desired.
 * @param expectedResponseStatus the expected {@link HttpResponseStatus} from remote.
 * @param contentSize the size of the content to attach with the request. No content attached if size is 0. If size >
 *                    1, then {@link HttpHeaderNames#TRANSFER_ENCODING} is set to {@link HttpHeaderValues#CHUNKED}.
 * @param keepAliveHint if {@code null}, no hint is added. If not {@code null}, hint is set to the given value
 * @return the {@link EmbeddedChannel} to use once this function is complete. If the channel did not close, this
 * function will return the {@code channel} instance that was passed, otherwise it returns a new channel.
 */
private EmbeddedChannel doKeepAliveTest(EmbeddedChannel channel, HttpMethod httpMethod,
    RestServiceErrorCode errorCode, HttpResponseStatus expectedResponseStatus, int contentSize,
    Boolean keepAliveHint) {
  boolean keepAlive = true;
  for (int i = 0; i < 2; i++) {
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    TestingUri uri = TestingUri.OnResponseCompleteWithNonRestException;
    if (errorCode != null) {
      uri = TestingUri.OnResponseCompleteWithRestException;
      httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, errorCode);
    }
    if (!keepAlive) {
      httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }
    if (keepAliveHint != null) {
      // this will get set in the NettyRequest when it is created
      httpHeaders.set(RestUtils.InternalKeys.KEEP_ALIVE_ON_ERROR_HINT, keepAliveHint);
    }
    byte[] content = null;
    if (contentSize > 0) {
      content = TestUtils.getRandomBytes(contentSize);
    }
    HttpRequest request = RestTestUtils.createFullRequest(httpMethod, uri.toString(), httpHeaders, content);
    if (contentSize > 1) {
      HttpUtil.setTransferEncodingChunked(request, true);
    } else {
      HttpUtil.setContentLength(request, contentSize);
    }
    channel.writeInbound(request);
    HttpResponse response = channel.readOutbound();
    assertEquals("Unexpected response status", expectedResponseStatus, response.status());
    if (!(response instanceof FullHttpResponse)) {
      // empty the channel
      while (channel.readOutbound() != null) {
      }
    }
    boolean shouldBeAlive = true;
    if (keepAliveHint != null) {
      shouldBeAlive = keepAliveHint;
    } else if (httpMethod.equals(HttpMethod.POST)) {
      shouldBeAlive = false;
    } else if (httpMethod.equals(HttpMethod.PUT)) {
      shouldBeAlive = contentSize == 0;
    }
    shouldBeAlive = shouldBeAlive && keepAlive && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(
        expectedResponseStatus);

    assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive());
    assertEquals("Connection header should be consistent with channel state", shouldBeAlive,
        HttpUtil.isKeepAlive(response));
    if (!shouldBeAlive) {
      channel.close();
      channel = createEmbeddedChannel();
    }
    keepAlive = !keepAlive;
  }
  return channel;
}