Java Code Examples for org.springframework.http.HttpMethod#valueOf()

The following examples show how to use org.springframework.http.HttpMethod#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
/**
 * Creates a matcher with the supplied pattern which will match the
 * specified Http method
 *
 * @param pattern 模式
 *            the ant pattern to use for matching
 * @param httpMethod HTTP方法
 *            the HTTP method. The {@code matches} method will return false
 *            if the incoming request doesn't doesn't have the same method.
 * @param caseSensitive 区分大小写
 *            true if the matcher should consider case, else false
 */
public MyAntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
    Assert.hasText(pattern, "Pattern cannot be null or empty");
    this.caseSensitive = caseSensitive;

    if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
        pattern = MATCH_ALL;
        matcher = null;
    } else {
        if(!caseSensitive) {
            pattern = pattern.toLowerCase();
        }

        // If the pattern ends with {@code /**} and has no other wildcards, then optimize to a sub-path match
        if (pattern.endsWith(MATCH_ALL) && pattern.indexOf('?') == -1 &&
                pattern.indexOf("*") == pattern.length() - 2) {
            matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3));
        } else {
            matcher = new SpringAntMatcher(pattern);
        }
    }

    this.pattern = pattern;
    this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
}
 
Example 2
/**
 * Returns true if the configured pattern (and HTTP-Method) match those of the supplied request.
 * 修改
 * @param request the request to match against. The ant pattern will be matched against the
 *    {@code servletPath} + {@code pathInfo} of the request.
 */
public boolean matches(HttpServletRequest request) {
	
	
    if (httpMethod != null && request.getMethod() != null && httpMethod != HttpMethod.valueOf(request.getMethod())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request '" + request.getMethod() + " " + getRequestPath(request) + "'"
                    + " doesn't match '" + httpMethod  + " " + pattern);
        }

        return false;
    }

    if (pattern.equals(MATCH_ALL)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request '" + getRequestPath(request) + "' matched by universal pattern '/**'");
        }

        return true;
    }
    
    //删除URL的路径和虚拟目录
    String url = UrlUtils.buildRequestUrl(request);
    return pathMatcher.match(pattern, url);
}
 
Example 3
Source Project: cucumber-rest-steps   File: RestSteps.java    License: MIT License 6 votes vote down vote up
private void callWithFile(String httpMethodString, String path, String file, Resource resource) {
  HttpMethod httpMethod = HttpMethod.valueOf(httpMethodString.toUpperCase());

  if (httpMethod.equals(HttpMethod.GET)) {
    throw new IllegalArgumentException("You can't submit a file in a GET call");
  }

  MultipartBodyBuilder builder = new MultipartBodyBuilder();
  builder.part(file, resource);

  responseSpec = webClient.method(httpMethod)
      .uri(path)
      .syncBody(builder.build())
      .exchange();
  expectBody = null;
}
 
Example 4
@Nullable
private HttpMethod getOverride(final RequestArguments arguments) {
    final Map<String, List<String>> headers = arguments.getHeaders();
    final String name = "X-HTTP-Method-Override";
    final List<String> overrides = headers.getOrDefault(name, emptyList());

    @Nullable final String override = overrides.stream().findFirst().orElse(null);

    if (override == null) {
        return null;
    }

    try {
        return HttpMethod.valueOf(override);
    } catch (final IllegalArgumentException e) {
        log.warn("Received invalid method in {} header: \"{}\"", name, override);
        return null;
    }
}
 
Example 5
Source Project: cloudbreak   File: Method.java    License: Apache License 2.0 6 votes vote down vote up
public static Method build(String methodName) {
    HttpMethod httpMethod = null;
    try {
        httpMethod = HttpMethod.valueOf(methodName.toUpperCase());
    } catch (IllegalArgumentException e) {
        for (HttpMethod checkMethod : HttpMethod.values()) {
            if (methodName.startsWith(checkMethod.name().toLowerCase())) {
                httpMethod = checkMethod;
                break;
            }
        }
    }
    if (httpMethod == null) {
        throw new IllegalArgumentException(methodName + " method name should start with http method (get, post, ...)");
    }
    return new Method(httpMethod, methodName);
}
 
Example 6
@SuppressWarnings("unchecked")
private Set<PluginPackageEntityDto> pullDynamicDataModelFromPlugin(PluginPackageDataModel dataModel) {
    Map<String, Object> parametersMap = new HashMap<>();
    String gatewayUrl = applicationProperties.getGatewayUrl();
    parametersMap.put("gatewayUrl", gatewayUrl);
    parametersMap.put("packageName", dataModel.getPackageName());
    String updatePath = dataModel.getUpdatePath();
    parametersMap.put("dataModelUrl", updatePath.startsWith("/") ? updatePath.substring(1) : updatePath);

    List<PluginPackageEntityDto> dynamicPluginPackageEntities = Collections.EMPTY_LIST;
    try {
        HttpHeaders httpHeaders = new HttpHeaders();
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(dataModelUrl);
        UriComponents uriComponents = uriComponentsBuilder.buildAndExpand(parametersMap);
        HttpMethod method = HttpMethod.valueOf(dataModel.getUpdateMethod());
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> requestEntity = new HttpEntity<>(httpHeaders);

        ResponseEntity<String> response = restTemplate.exchange(uriComponents.toString(), method, requestEntity, String.class);
        if (StringUtils.isBlank(response.getBody()) || response.getStatusCode().isError()) {
            throw new WecubeCoreException(response.toString());
        }
        CommonResponseDto responseDto = JsonUtils.toObject(response.getBody(), CommonResponseDto.class);
        if (!CommonResponseDto.STATUS_OK.equals(responseDto.getStatus())) {
            String msg = String.format("Request error! The error message is [%s]", responseDto.getMessage());
            logger.error(msg);
            throw new WecubeCoreException(msg);
        }
        dynamicPluginPackageEntities = JsonUtils.toList(JsonUtils.toJsonString(responseDto.getData()), PluginPackageEntityDto.class);
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    }
    return Sets.newLinkedHashSet(dynamicPluginPackageEntities);
}
 
Example 7
@Override
public void apply(OperationContext context) {
    HandlerMethod handlerMethod = context.getHandlerMethod();

    ApiOperation apiOperationAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class);
    HttpMethod httpMethod = null;
    if (apiOperationAnnotation != null && StringUtils.hasText(apiOperationAnnotation.httpMethod())) {
        String apiMethod = apiOperationAnnotation.httpMethod();
        try {
            RequestMethod.valueOf(apiMethod);
        } catch (IllegalArgumentException e) {
            log.error("Invalid http method: " + apiMethod + "Valid ones are [" + RequestMethod.values() + "]", e);
        }
        httpMethod = HttpMethod.valueOf(apiMethod);
    } else {
        RequestMapping requestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
        RequestMethod[] methods = requestMapping.method();
        if (CollectionUtil.isNotEmpty(methods)) {
            httpMethod = HttpMethod.valueOf(CollectionUtil.getFirst(methods).toString());
        }
    }

    if (httpMethod == null) {
        httpMethod = HttpMethod.GET;
    }

    context.operationBuilder().method(httpMethod);
}
 
Example 8
Source Project: cucumber-rest-steps   File: RestSteps.java    License: MIT License 5 votes vote down vote up
private void call(String httpMethodString, URI uri, Object requestObj) throws JSONException {
  HttpMethod httpMethod = HttpMethod.valueOf(httpMethodString.toUpperCase());

  if (httpMethod.equals(HttpMethod.GET) && requestObj != null) {
    throw new IllegalArgumentException("You can't pass data in a GET call");
  }

  final String path = uri.toString();
  if (path.contains("$.")) {
    initExpectBody();
    Pattern pattern = Pattern.compile("(((\\$.*)\\/.*)|(\\$.*))");
    Matcher matcher = pattern.matcher(path);
    assertTrue(matcher.find());
    final String jsonPath = matcher.group(0);
    final byte[] responseBody = expectBody.jsonPath(jsonPath).exists().returnResult().getResponseBody();
    final String value = ((JSONObject) JSONParser.parseJSON(new String(responseBody))).getString(jsonPath.replace("$.", ""));
    uri = URI.create(path.replace(jsonPath, value));
  }

  final RequestBodySpec requestBodySpec = webClient.method(httpMethod).uri(uri);
  if (requestObj != null) {
    requestBodySpec.syncBody(requestObj);
    requestBodySpec.contentType(MediaType.APPLICATION_JSON);
  }

  if (headers != null) {
    headers.forEach((key, value) -> requestBodySpec.header(key, value.toArray(new String[0])));
  }

  responseSpec = requestBodySpec.exchange();
  expectBody = null;
  headers = null;
}
 
Example 9
@Override
public boolean matches(HttpServletRequest request) {
    if(httpMethodUsed) {
        // Check if the method actually exists
        try {
            HttpMethod.valueOf(request.getMethod());
        } catch(IllegalArgumentException iae) {
            // Since it's not possible to register matchers for an unknown method, we know the path/method will
            // never match. Return false to prevent an exception in the wrapped matcher
            return false;
        }
    }
    return wrapped.matches(request);
}
 
Example 10
/**
 * 根据是否实现了某个接口,返回侦听
 *
 * @param serviceCode
 * @return
 * @since 1.8
 */
public static List<ServiceDataFlowListener> getListeners(String serviceCode, String httpMethod) {

    Assert.hasLength(serviceCode, "获取需要发布的事件处理侦听时,传递事件为空,请检查");

    String needCachedServiceCode = serviceCode + httpMethod;
    //先从缓存中获取,为了提升效率
    if (cacheListenersMap.containsKey(needCachedServiceCode)) {
        return cacheListenersMap.get(needCachedServiceCode);
    }

    List<ServiceDataFlowListener> dataFlowListeners = new ArrayList<ServiceDataFlowListener>();
    for (String listenerBeanName : getListeners()) {
        ServiceDataFlowListener listener = ApplicationContextFactory.getBean(listenerBeanName, ServiceDataFlowListener.class);
        if (serviceCode.equals(listener.getServiceCode())
                && listener.getHttpMethod() == HttpMethod.valueOf(httpMethod)) {
            dataFlowListeners.add(listener);
        }
        //特殊处理 透传类接口
        if (ServiceCodeConstant.SERVICE_CODE_DO_SERVICE_TRANSFER.equals(listener.getServiceCode())
                && ServiceCodeConstant.SERVICE_CODE_DO_SERVICE_TRANSFER.equals(serviceCode)) {
            dataFlowListeners.add(listener);
        }
    }

    //这里排序
    DataFlowListenerOrderComparator.sort(dataFlowListeners);


    //将数据放入缓存中
    if (dataFlowListeners.size() > 0) {
        cacheListenersMap.put(needCachedServiceCode, dataFlowListeners);
    }
    return dataFlowListeners;
}
 
Example 11
@Override
public boolean matches(HttpServletRequest request) {
    if (httpMethodUsed) {
        // Check if the method actually exists
        try {
            HttpMethod.valueOf(request.getMethod());
        } catch (IllegalArgumentException iae) {
            // Since it's not possible to register matchers for an unknown method, we know the path/method will
            // never match. Return false to prevent an exception in the wrapped matcher
            return false;
        }
    }
    return wrapped.matches(request);
}
 
Example 12
Source Project: davos   File: HttpAPICallAction.java    License: MIT License 5 votes vote down vote up
public HttpAPICallAction(String url, String method, String contentType, String body) {

        this.url = url;
        this.method = HttpMethod.valueOf(method);
        this.contentType = contentType;
        this.body = body;
    }
 
Example 13
Source Project: hawkbit   File: DosFilter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {

    if (!shouldInclude(request)) {
        filterChain.doFilter(request, response);
        return;
    }

    boolean processChain;

    final String ip = IpUtil.getClientIpFromRequest(request, forwardHeader).getHost();

    if (checkIpFails(ip)) {
        processChain = handleMissingIpAddress(response);
    } else {
        processChain = checkAgainstBlacklist(response, ip);

        if (processChain && (whitelist == null || !whitelist.matcher(ip).find())) {
            // read request
            if (HttpMethod.valueOf(request.getMethod()) == HttpMethod.GET) {
                processChain = handleReadRequest(response, ip);
            }
            // write request
            else {
                processChain = handleWriteRequest(response, ip);
            }
        }
    }

    if (processChain) {
        filterChain.doFilter(request, response);
    }
}
 
Example 14
/**
 * Creates a matcher with the supplied pattern which will match the specified Http
 * method
 *
 * @param pattern the ant pattern to use for matching
 * @param httpMethod the HTTP method. The {@code matches} method will return false if
 * the incoming request doesn't doesn't have the same method.
 * @param caseSensitive true if the matcher should consider case, else false
 */
public HardeningAntPathRequestMatcher(String pattern, String httpMethod,
		boolean caseSensitive) {
	Assert.hasText(pattern, "Pattern cannot be null or empty");
	this.caseSensitive = caseSensitive;

	if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
		pattern = MATCH_ALL;
		this.matcher = null;
	}
	else {
		// If the pattern ends with {@code /**} and has no other wildcards or path
		// variables, then optimize to a sub-path match
		if (pattern.endsWith(MATCH_ALL)
				&& (pattern.indexOf('?') == -1 && pattern.indexOf('{') == -1
						&& pattern.indexOf('}') == -1)
				&& pattern.indexOf("*") == pattern.length() - 2) {
			this.matcher = new SubpathMatcher(
					pattern.substring(0, pattern.length() - 3), caseSensitive);
		}
		else {
			this.matcher = new SpringAntMatcher(pattern, caseSensitive);
		}
	}

	this.pattern = pattern;
	this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod)
			: null;
}
 
Example 15
/**
 * Provides a save way of obtaining the HttpMethod from a String. If the method is
 * invalid, returns null.
 *
 * @param method the HTTP method to use.
 *
 * @return the HttpMethod or null if method is invalid.
 */
private static HttpMethod valueOf(String method) {
	try {
		return HttpMethod.valueOf(method);
	}
	catch (IllegalArgumentException e) {
	}

	return null;
}
 
Example 16
Source Project: spring-openapi   File: OperationsTransformer.java    License: MIT License 4 votes vote down vote up
private HttpMethod getSpringMethod(RequestMethod[] method) {
	if (method == null || method.length == 0) {
		throw new IllegalArgumentException("HttpMethod must be specified on RequestMapping annotated method");
	}
	return HttpMethod.valueOf(method[0].name());
}
 
Example 17
Source Project: spring-openapi   File: OperationsTransformer.java    License: MIT License 4 votes vote down vote up
private HttpMethod getSpringMethod(RequestMethod method) {
	if (method == null) {
		throw new IllegalArgumentException("HttpMethod must be specified on RequestMapping annotated method");
	}
	return HttpMethod.valueOf(method.name());
}
 
Example 18
public HttpMethod getMethod() {
    return HttpMethod.valueOf(getMethodValue());
}
 
Example 19
public HttpMethod getMethod() {
    return HttpMethod.valueOf(getMethodValue());
}
 
Example 20
protected HttpMethod mapStringToHttpMethod(String method) {
	return HttpMethod.valueOf(method);
}