Java Code Examples for org.springframework.web.bind.annotation.RequestMapping#method()

The following examples show how to use org.springframework.web.bind.annotation.RequestMapping#method() . 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: CrossOriginTests.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 2
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annot != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annot.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annot.method()),
			new ParamsRequestCondition(annot.params()),
			new HeadersRequestCondition(annot.headers()),
			new ConsumesRequestCondition(annot.consumes(), annot.headers()),
			new ProducesRequestCondition(annot.produces(), annot.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 3
Source File: CrossOriginTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 4
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annot != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annot.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annot.method()),
			new ParamsRequestCondition(annot.params()),
			new HeadersRequestCondition(annot.headers()),
			new ConsumesRequestCondition(annot.consumes(), annot.headers()),
			new ProducesRequestCondition(annot.produces(), annot.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 5
Source File: RequestMappingInfoHandlerMappingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annotation.method()),
			new ParamsRequestCondition(annotation.params()),
			new HeadersRequestCondition(annotation.headers()),
			new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
			new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 6
Source File: CrossOriginTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 7
Source File: DefaultAnnotationHandlerMapping.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the given type-level mapping metadata against the current request,
 * checking HTTP request method and parameter conditions.
 * @param mapping the mapping metadata to validate
 * @param request current HTTP request
 * @throws Exception if validation failed
 */
protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception {
	RequestMethod[] mappedMethods = mapping.method();
	if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) {
		String[] supportedMethods = new String[mappedMethods.length];
		for (int i = 0; i < mappedMethods.length; i++) {
			supportedMethods[i] = mappedMethods[i].name();
		}
		throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods);
	}

	String[] mappedParams = mapping.params();
	if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) {
		throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap());
	}

	String[] mappedHeaders = mapping.headers();
	if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) {
		throw new ServletRequestBindingException("Header conditions \"" +
				StringUtils.arrayToDelimitedString(mappedHeaders, ", ") +
				"\" not met for actual request");
	}
}
 
Example 8
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isHandlerMethod(Method method) {
	if (this.mappings.containsKey(method)) {
		return true;
	}
	RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (mapping != null) {
		String[] patterns = mapping.value();
		RequestMethod[] methods = new RequestMethod[0];
		String[] params = new String[0];
		String[] headers = new String[0];
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.method(), getTypeLevelMapping().method())) {
			methods = mapping.method();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.params(), getTypeLevelMapping().params())) {
			params = mapping.params();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.headers(), getTypeLevelMapping().headers())) {
			headers = mapping.headers();
		}
		RequestMappingInfo mappingInfo = new RequestMappingInfo(patterns, methods, params, headers);
		this.mappings.put(method, mappingInfo);
		return true;
	}
	return false;
}
 
Example 9
Source File: DefaultAnnotationHandlerMapping.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate the given type-level mapping metadata against the current request,
 * checking HTTP request method and parameter conditions.
 * @param mapping the mapping metadata to validate
 * @param request current HTTP request
 * @throws Exception if validation failed
 */
protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception {
	RequestMethod[] mappedMethods = mapping.method();
	if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) {
		String[] supportedMethods = new String[mappedMethods.length];
		for (int i = 0; i < mappedMethods.length; i++) {
			supportedMethods[i] = mappedMethods[i].name();
		}
		throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods);
	}

	String[] mappedParams = mapping.params();
	if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) {
		throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap());
	}

	String[] mappedHeaders = mapping.headers();
	if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) {
		throw new ServletRequestBindingException("Header conditions \"" +
				StringUtils.arrayToDelimitedString(mappedHeaders, ", ") +
				"\" not met for actual request");
	}
}
 
Example 10
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean isHandlerMethod(Method method) {
	if (this.mappings.containsKey(method)) {
		return true;
	}
	RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (mapping != null) {
		String[] patterns = mapping.value();
		RequestMethod[] methods = new RequestMethod[0];
		String[] params = new String[0];
		String[] headers = new String[0];
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.method(), getTypeLevelMapping().method())) {
			methods = mapping.method();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.params(), getTypeLevelMapping().params())) {
			params = mapping.params();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.headers(), getTypeLevelMapping().headers())) {
			headers = mapping.headers();
		}
		RequestMappingInfo mappingInfo = new RequestMappingInfo(patterns, methods, params, headers);
		this.mappings.put(method, mappingInfo);
		return true;
	}
	return false;
}
 
Example 11
Source File: JacksonModelAttributeSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
protected boolean isRequestMethodGet(HandlerMethod method) {
    RequestMapping requestMapping = method.getMethodAnnotation(RequestMapping.class);
    return requestMapping == null
            || requestMapping.method() == null
            || Arrays.stream(requestMapping.method()).anyMatch(requestMethod -> {
        return requestMethod == RequestMethod.GET;
    });
}
 
Example 12
Source File: DefaultAnnotationHandlerMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register all handlers specified in the Portlet mode map for the corresponding modes.
 * @throws org.springframework.beans.BeansException if the handler couldn't be registered
 */
protected void detectHandlers() throws BeansException {
	ApplicationContext context = getApplicationContext();
	String[] beanNames = context.getBeanNamesForType(Object.class);
	for (String beanName : beanNames) {
		Class<?> handlerType = context.getType(beanName);
		RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
		if (mapping != null) {
			// @RequestMapping found at type level
			String[] modeKeys = mapping.value();
			String[] params = mapping.params();
			boolean registerHandlerType = true;
			if (modeKeys.length == 0 || params.length == 0) {
				registerHandlerType = !detectHandlerMethods(handlerType, beanName, mapping);
			}
			if (registerHandlerType) {
				AbstractParameterMappingPredicate predicate = new TypeLevelMappingPredicate(
						params, mapping.headers(), mapping.method());
				for (String modeKey : modeKeys) {
					registerHandler(new PortletMode(modeKey), beanName, predicate);
				}
			}
		}
		else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {
			detectHandlerMethods(handlerType, beanName, mapping);
		}
	}
}
 
Example 13
Source File: RequestMappingResolver.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RequestMappingResolveResult resolveOwnPath(Method method) {
    RequestMethod requestMethod =null;
    String path =null;
    
    ApiRequestMappingAutoWithMethodName apiRequestMappingAutoWithMethodName = AnnotationUtil.getAnnotation(method,  ApiRequestMappingAutoWithMethodName.class);
    
    RequestMapping requestMapping = AnnotatedElementUtils.getMergedAnnotation(method, RequestMapping.class);
    String requestMappingValue = getRequestMappingValue(requestMapping);
    
    //判断requestMapping是否在method上
    boolean requestMappingOnMethod =method.isAnnotationPresent(RequestMapping.class);
    
    if (!requestMappingOnMethod && apiRequestMappingAutoWithMethodName != null && StringUtil.isBlank(requestMappingValue)) {
        String methodName = method.getName();
        path =StringUtil.startWithSlash(methodName);
        requestMethod = apiRequestMappingAutoWithMethodName.method();
    } else if (StringUtil.isNotBlank(requestMappingValue)) {
        RequestMethod[] requestMethods = requestMapping.method();
        requestMethod =  CollectionUtil.getFirst(requestMethods);
        path =requestMappingValue;
    }
    
    if (requestMethod == null && requestMapping!=null) {
        RequestMethod[] netMethods = requestMapping.method();
        requestMethod =  CollectionUtil.getFirst(netMethods);
    }
    
    return new RequestMappingResolveResult(path, requestMethod);
}
 
Example 14
Source File: SpringMvcContract.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
		Annotation methodAnnotation, Method method) {
	if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
			.annotationType().isAnnotationPresent(RequestMapping.class)) {
		return;
	}

	RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
	// HTTP Method
	RequestMethod[] methods = methodMapping.method();
	if (methods.length == 0) {
		methods = new RequestMethod[] { RequestMethod.GET };
	}
	checkOne(method, methods, "method");
	data.template().method(Request.HttpMethod.valueOf(methods[0].name()));

	// path
	checkAtMostOne(method, methodMapping.value(), "value");
	if (methodMapping.value().length > 0) {
		String pathValue = emptyToNull(methodMapping.value()[0]);
		if (pathValue != null) {
			pathValue = resolve(pathValue);
			if (!pathValue.equals("/")) {
				data.template().uri(pathValue, true);
			}
		}
	}

	// produces
	parseProduces(data, method, methodMapping);

	// consumes
	parseConsumes(data, method, methodMapping);

	// headers
	parseHeaders(data, method, methodMapping);

	data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 15
Source File: OpenFeignSpringMvcContract.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation)
        && !methodAnnotation.annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);

    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[] {RequestMethod.GET};
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);

            if (!pathValue.startsWith("/") && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    parseProduces(data, method, methodMapping);

    parseConsumes(data, method, methodMapping);

    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 16
Source File: RoleResourceAspect.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 判断当前用户对访问的方法是否有权限
 *
 * @param pjp            方法
 * @param requestMapping 方法上的annotation
 *
 * @return
 *
 * @throws Throwable
 */
@Around("anyPublicMethod() && @annotation(requestMapping) && !@annotation(com.baidu.dsp.common.annotation.NoAuth)")
public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

    // 获取method上的url,若未标注value则默认为空字符串
    String[] values = requestMapping.value();
    String methodUrl = "";
    if (values.length != 0) {
        methodUrl = values[0];
    }

    String clsUrl = pjp.getTarget().getClass().getAnnotation(RequestMapping.class).value()[0];

    // 拼接method和class上标注的url
    if (!clsUrl.endsWith(RoleResourceConstant.URL_SPLITOR) &&
            !methodUrl.startsWith(RoleResourceConstant.URL_SPLITOR)) {
        clsUrl += RoleResourceConstant.URL_SPLITOR;
    }

    String urlPattarn = clsUrl + methodUrl;
    if (!urlPattarn.endsWith(RoleResourceConstant.URL_SPLITOR)) {
        urlPattarn += RoleResourceConstant.URL_SPLITOR;
    }

    if (noAuthCheckUrl != null && noAuthCheckUrl.contains(urlPattarn)) {

        LOG.info("don't need to check this url: " + urlPattarn);
    } else {

        // 获取method上标注的http method,若未标注method则默认为GET
        RequestMethod[] methods = requestMapping.method();
        RequestMethod methodType = RequestMethod.GET;
        if (methods.length != 0) {
            methodType = methods[0];
        }

        String urlInfo = urlPattarn + ", method:" + methodType.toString();

        // 获取用户角色
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor == null) {
            LOG.warn("No session visitor!");
            throw new AccessDeniedException("No session visitor! " + urlInfo);
        }
        Integer roleId = visitor.getRoleId();
        String visitorInfo = ", UserId:" + visitor.getId() + ", RoleId:" + roleId;

        Boolean isPriviledged = true;
        // 判断用户是否有权限访问方法
        if (!this.isMethodAccessible(urlPattarn, methodType, roleId)) {
            isPriviledged = false;
            throw new AccessDeniedException("Access Denied: " + urlInfo + visitorInfo);
        }
        LOG.info("Accessing URL:" + urlInfo + visitorInfo + ", Is priviledged:" + isPriviledged.toString());
    }

    Object rtnOb = null;

    try {
        // 执行方法
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOG.info(t.getMessage());
        throw t;
    }

    return rtnOb;
}
 
Example 17
Source File: VenusSpringMvcContract.java    From venus-cloud-feign with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
                                         Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
            .annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
    // HTTP Method
    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[] { RequestMethod.GET };
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    // path
    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);
            // Append path from @RequestMapping if value is present on method
            if (!pathValue.startsWith("/")
                    && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    // produces
    parseProduces(data, method, methodMapping);

    // consumes
    parseConsumes(data, method, methodMapping);

    // headers
    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 18
Source File: SpringMvcContract.java    From raptor with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
                                         Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
            .annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
    // HTTP Method
    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[]{RequestMethod.GET};
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    // path
    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);
            // Append path from @RequestMapping if value is present on method
            if (!pathValue.startsWith("/")
                    && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    // produces
    parseProduces(data, method, methodMapping);

    // consumes
    parseConsumes(data, method, methodMapping);

    // headers
    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 19
Source File: SpringMvcApiReader.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
public Swagger read(SpringResource resource) {
    if (swagger == null) {
        swagger = new Swagger();
    }
    List<Method> methods = resource.getMethods();
    Map<String, Tag> tags = new HashMap<String, Tag>();

    List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>();

    // Add the description from the controller api
    Class<?> controller = resource.getControllerClass();
    RequestMapping controllerRM = findMergedAnnotation(controller, RequestMapping.class);

    String[] controllerProduces = new String[0];
    String[] controllerConsumes = new String[0];
    if (controllerRM != null) {
        controllerConsumes = controllerRM.consumes();
        controllerProduces = controllerRM.produces();
    }

    if (controller.isAnnotationPresent(Api.class)) {
        Api api = findMergedAnnotation(controller, Api.class);
        if (!canReadApi(false, api)) {
            return swagger;
        }
        tags = updateTagsForApi(null, api);
        resourceSecurities = getSecurityRequirements(api);
    }

    resourcePath = resource.getControllerMapping();

    //collect api from method with @RequestMapping
    Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods);

    for (String path : apiMethodMap.keySet()) {
        for (Method method : apiMethodMap.get(path)) {
            RequestMapping requestMapping = findMergedAnnotation(method, RequestMapping.class);
            if (requestMapping == null) {
                continue;
            }
            ApiOperation apiOperation = findMergedAnnotation(method, ApiOperation.class);
            if (apiOperation != null && apiOperation.hidden()) {
                continue;
            }

            Map<String, String> regexMap = new HashMap<String, String>();
            String operationPath = parseOperationPath(path, regexMap);

            //http method
            for (RequestMethod requestMethod : requestMapping.method()) {
                String httpMethod = requestMethod.toString().toLowerCase();
                Operation operation = parseMethod(method, requestMethod);

                updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation);

                updateOperationProtocols(apiOperation, operation);

                String[] apiProduces = requestMapping.produces();
                String[] apiConsumes = requestMapping.consumes();

                apiProduces = (apiProduces.length == 0) ? controllerProduces : apiProduces;
                apiConsumes = (apiConsumes.length == 0) ? controllerConsumes : apiConsumes;

                apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation);
                apiProduces = updateOperationProduces(new String[0], apiProduces, operation);

                updateTagsForOperation(operation, apiOperation);
                updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation);
                updatePath(operationPath, httpMethod, operation);
            }
        }
    }
    return swagger;
}
 
Example 20
Source File: RoleResourceAspect.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 判断当前用户对访问的方法是否有权限
 *
 * @param pjp            方法
 * @param requestMapping 方法上的annotation
 *
 * @return
 *
 * @throws Throwable
 */
@Around("anyPublicMethod() && @annotation(requestMapping) && !@annotation(com.baidu.dsp.common.annotation.NoAuth)")
public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

    // 获取method上的url,若未标注value则默认为空字符串
    String[] values = requestMapping.value();
    String methodUrl = "";
    if (values.length != 0) {
        methodUrl = values[0];
    }

    String clsUrl = pjp.getTarget().getClass().getAnnotation(RequestMapping.class).value()[0];

    // 拼接method和class上标注的url
    if (!clsUrl.endsWith(RoleResourceConstant.URL_SPLITOR) &&
            !methodUrl.startsWith(RoleResourceConstant.URL_SPLITOR)) {
        clsUrl += RoleResourceConstant.URL_SPLITOR;
    }

    String urlPattarn = clsUrl + methodUrl;
    if (!urlPattarn.endsWith(RoleResourceConstant.URL_SPLITOR)) {
        urlPattarn += RoleResourceConstant.URL_SPLITOR;
    }

    if (noAuthCheckUrl != null && noAuthCheckUrl.contains(urlPattarn)) {

        LOG.info("don't need to check this url: " + urlPattarn);
    } else {

        // 获取method上标注的http method,若未标注method则默认为GET
        RequestMethod[] methods = requestMapping.method();
        RequestMethod methodType = RequestMethod.GET;
        if (methods.length != 0) {
            methodType = methods[0];
        }

        String urlInfo = urlPattarn + ", method:" + methodType.toString();

        // 获取用户角色
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor == null) {
            LOG.warn("No session visitor!");
            throw new AccessDeniedException("No session visitor! " + urlInfo);
        }
        Integer roleId = visitor.getRoleId();
        String visitorInfo = ", UserId:" + visitor.getId() + ", RoleId:" + roleId;

        Boolean isPriviledged = true;
        // 判断用户是否有权限访问方法
        if (!this.isMethodAccessible(urlPattarn, methodType, roleId)) {
            isPriviledged = false;
            throw new AccessDeniedException("Access Denied: " + urlInfo + visitorInfo);
        }
        LOG.info("Accessing URL:" + urlInfo + visitorInfo + ", Is priviledged:" + isPriviledged.toString());
    }

    Object rtnOb = null;

    try {
        // 执行方法
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOG.info(t.getMessage());
        throw t;
    }

    return rtnOb;
}