Java Code Examples for org.springframework.web.bind.annotation.RestController

The following examples show how to use org.springframework.web.bind.annotation.RestController. 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: smart-admin   Source File: SmartSwaggerDynamicGroupConfig.java    License: MIT License 6 votes vote down vote up
private Predicate<RequestHandler> getControllerPredicate() {
    groupName = groupList.get(groupIndex);
    List<String> apiTags = groupMap.get(groupName);
    Predicate<RequestHandler> methodPredicate = (input) -> {
        Api api = null;
        Optional<Api> apiOptional = input.findControllerAnnotation(Api.class);
        if (apiOptional.isPresent()) {
            api = apiOptional.get();
        }
        List<String> tags = Arrays.asList(api.tags());
        if (api != null && apiTags.containsAll(tags)) {
            return true;
        }
        return false;
    };
    groupIndex++;
    return Predicates.and(RequestHandlerSelectors.withClassAnnotation(RestController.class), methodPredicate);
}
 
Example 2
Source Project: Jpom   Source File: WebAopLog.java    License: MIT License 6 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
    if (aopLogInterface != null) {
        aopLogInterface.before(joinPoint);
    }
    // 接收到请求,记录请求内容
    IS_LOG.set(ExtConfigBean.getInstance().isConsoleLogReqResponse());
    Signature signature = joinPoint.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody == null) {
            RestController restController = joinPoint.getTarget().getClass().getAnnotation(RestController.class);
            if (restController == null) {
                IS_LOG.set(false);
            }
        }
    }
}
 
Example 3
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) {
    setRequestContext(request);
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    //判断当前请求是否为接口
    boolean hasResponseBody = method.isAnnotationPresent(ResponseBody.class);
    boolean hasRestController = handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
    RequestContext requestContext = WebContextFacade.getRequestContext();
    requestContext.setApiRequest(hasResponseBody || hasRestController);
    WebContextFacade.setRequestContext(requestContext);
    return true;
}
 
Example 4
Source Project: java-tutorial   Source File: SwaggerConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .pathMapping("/")
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build().apiInfo(new ApiInfoBuilder()
                    .title("OAuth2.0 API ")
                    .description("api docs")
                    .version("1.0")
                    .contact(new Contact("jarvis", "github.com", "[email protected]"))
                    .license("The Apache License")
                    .licenseUrl("https://www.github.com")
                    .build());
}
 
Example 5
Source Project: seed   Source File: LogConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Pointcut getPointcut() {
    return new StaticMethodMatcherPointcut(){
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            //若类上面注解了DisableLog,则不打印日志(仅此类,不包括该类中被调用的类)
            if(targetClass.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若方法上面注解了DisableLog,则不打印日志
            if(method.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若类上面注解了EnableLog,则打印日志
            if(targetClass.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //若方法上面注解了EnableLog,则打印日志
            if(method.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //默认的:打印标注了RestController的类、以及ResponseBody的方法,的日志
            return targetClass.isAnnotationPresent(RestController.class) || method.isAnnotationPresent(ResponseBody.class);
        }
    };
}
 
Example 6
@Bean
public Docket petApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(withClassAnnotation(RestController.class))
            .build()
            .pathMapping("/")
            .enableUrlTemplating(true)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(
                    HttpServletRequest.class,
                    HttpServletResponse.class,
                    HttpSession.class,
                    Pageable.class,
                    Errors.class
            );
}
 
Example 7
private ExceptionResponseType getExceptionResponseType(HandlerMethod handlerMethod) {
  ExceptionResponseType exceptionResponseType;

  Class<?> beanType = handlerMethod.getBeanType();
  if (ApiController.class.isAssignableFrom(beanType)) {
    exceptionResponseType = PROBLEM;
  } else if (handlerMethod.hasMethodAnnotation(ResponseStatus.class)
      || handlerMethod.hasMethodAnnotation(ResponseBody.class)
      || beanType.isAnnotationPresent(ResponseBody.class)
      || beanType.isAnnotationPresent(RestController.class)) {
    exceptionResponseType = ERROR_MESSAGES;
  } else {
    exceptionResponseType = MODEL_AND_VIEW;
  }

  return exceptionResponseType;
}
 
Example 8
@Override
public boolean canProcess(Class<?> cls) {
  if (cls.getAnnotation(RestController.class) != null) {
    return true;
  }
  return false;
}
 
Example 9
private static boolean canProcess(Class<?> loadClass) {

    if (loadClass == null) {
      return false;
    }
    RestSchema restSchema = loadClass.getAnnotation(RestSchema.class);
    if (restSchema != null) {
      return true;
    }

    RestController controller = loadClass.getAnnotation(RestController.class);
    if (controller != null) {
      return true;
    }

    RpcSchema rpcSchema = loadClass.getAnnotation(RpcSchema.class);
    if (rpcSchema != null) {
      return true;
    }

    RequestMapping requestMapping = loadClass.getAnnotation(RequestMapping.class);
    if (requestMapping != null) {
      return true;
    }

    Path pathAnnotation = loadClass.getAnnotation(Path.class);
    if (pathAnnotation != null) {
      return true;
    }
    return false;
  }
 
Example 10
@Test
public void testPrivateCanProcess() throws Exception {
  DefaultContractsGenerator defaultContractsGenerator = new DefaultContractsGenerator();
  Method method = defaultContractsGenerator.getClass().getDeclaredMethod("canProcess", Class.class);
  method.setAccessible(true);

  assertThat(method.invoke(defaultContractsGenerator, new Object[] {null}), is(false));

  Class mockClass;
  ContractTestUtil contractTestUtil = new ContractTestUtil();

  CtClass ctClass = contractTestUtil.createCtClass("TestCanProcess");
  assertThat(method.invoke("TestCanProcess", ctClass.toClass()), is(false));

  mockClass = contractTestUtil.putAnnotationToClass("TestRestSchema", RestSchema.class);
  assertThat(method.invoke("TestRestSchema", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRestController", RestController.class);
  assertThat(method.invoke("TestRestController", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRpcSchema", RpcSchema.class);
  assertThat(method.invoke("TestRpcSchema", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRequestMapping", RequestMapping.class);
  assertThat(method.invoke("TestRequestMapping", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestPath", Path.class);
  assertThat(method.invoke("TestPath", mockClass), is(true));
}
 
Example 11
Source Project: spring-openapi   Source File: OpenAPIGenerator.java    License: MIT License 5 votes vote down vote up
private Map<String, PathItem> createPathExtensions() {
ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

      List<Class<?>> controllerClasses = new ArrayList<>();
      List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
      for (String controllerPackage : packagesWithoutRegex) {
          logger.debug("Scanning controller package=[{}]", controllerPackage);
          for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
              logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
              controllerClasses.add(getClass(beanDefinition));
          }
      }
      return operationsTransformer.transformOperations(controllerClasses);
  }
 
Example 12
Source Project: spring-openapi   Source File: OpenAPIV2Generator.java    License: MIT License 5 votes vote down vote up
private Map<String, Path> createPaths(OpenApiV2GeneratorConfig config) {
	ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
	scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

	List<Class<?>> controllerClasses = new ArrayList<>();
	List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
	for (String controllerPackage : packagesWithoutRegex) {
		logger.debug("Scanning controller package=[{}]", controllerPackage);
		for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
			logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
			controllerClasses.add(getClass(beanDefinition));
		}
	}
	return operationsTransformer.transformOperations(controllerClasses, config);
}
 
Example 13
@Test
public void pathPrefix() throws Exception {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
Example 14
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns());
}
 
Example 15
Source Project: springdoc-openapi   Source File: OpenAPIBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Build.
 */
public void build() {
	Optional<OpenAPIDefinition> apiDef = getOpenAPIDefinition();

	if (openAPI == null) {
		this.calculatedOpenAPI = new OpenAPI();
		this.calculatedOpenAPI.setComponents(new Components());
		this.calculatedOpenAPI.setPaths(new Paths());
	}
	else
		this.calculatedOpenAPI = openAPI;

	if (apiDef.isPresent()) {
		buildOpenAPIWithOpenAPIDefinition(calculatedOpenAPI, apiDef.get());
	}
	// Set default info
	else if (calculatedOpenAPI.getInfo() == null) {
		Info infos = new Info().title(DEFAULT_TITLE).version(DEFAULT_VERSION);
		calculatedOpenAPI.setInfo(infos);
	}
	// Set default mappings
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RestController.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RequestMapping.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(Controller.class));

	// add security schemes
	this.calculateSecuritySchemes(calculatedOpenAPI.getComponents());
	openApiBuilderCustomisers.ifPresent(customisers -> customisers.forEach(customiser -> customiser.customise(this)));
}
 
Example 16
Source Project: Jpom   Source File: BaseJpomInterceptor.java    License: MIT License 5 votes vote down vote up
static boolean isPage(HandlerMethod handlerMethod) {
    ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
    if (responseBody == null) {
        RestController restController = handlerMethod.getBeanType().getAnnotation(RestController.class);
        return restController == null;
    }
    return false;
}
 
Example 17
Source Project: archunit-examples   Source File: SpringCodingRulesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void springSingletonComponentsShouldOnlyHaveFinalFields() {
  ArchRule rule = ArchRuleDefinition.classes()
    .that().areAnnotatedWith(Service.class)
    .or().areAnnotatedWith(Component.class)
    .and().areNotAnnotatedWith(ConfigurationProperties.class)
    .or().areAnnotatedWith(Controller.class)
    .or().areAnnotatedWith(RestController.class)
    .or().areAnnotatedWith(Repository.class)
    .should().haveOnlyFinalFields();
  rule.check(classes);
}
 
Example 18
Source Project: sbp   Source File: PluginRequestMappingHandlerMapping.java    License: Apache License 2.0 5 votes vote down vote up
public Set<Object> getControllerBeans(SpringBootPlugin springBootPlugin) {
    LinkedHashSet<Object> beans = new LinkedHashSet<>();
    ApplicationContext applicationContext = springBootPlugin.getApplicationContext();
    //noinspection unchecked
    Set<String> sharedBeanNames = (Set<String>) applicationContext.getBean(
            SpringBootstrap.BEAN_IMPORTED_BEAN_NAMES);
    beans.addAll(applicationContext.getBeansWithAnnotation(Controller.class)
            .entrySet().stream().filter(beanEntry -> !sharedBeanNames.contains(beanEntry.getKey()))
            .map(Map.Entry::getValue).collect(Collectors.toList()));
    beans.addAll(applicationContext.getBeansWithAnnotation(RestController.class)
            .entrySet().stream().filter(beanEntry -> !sharedBeanNames.contains(beanEntry.getKey()))
            .map(Map.Entry::getValue).collect(Collectors.toList()));
    return beans;
}
 
Example 19
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
Example 20
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns());
}
 
Example 21
Source Project: FATE-Serving   Source File: GlobalResponseController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean supports(MethodParameter methodParameter, Class converterType) {

    Boolean isRest = AnnotationUtils.isAnnotationDeclaredLocally(
            RestController.class, methodParameter.getContainingClass());
    ResponseBody responseBody = AnnotationUtils.findAnnotation(
            methodParameter.getMethod(), ResponseBody.class);

    if (responseBody != null || isRest) {
        return true;
    } else {
        return false;
    }

}
 
Example 22
Source Project: soul   Source File: SpringMvcClientBeanPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(@NonNull final Object bean, @NonNull final String beanName) throws BeansException {
    if (soulSpringMvcConfig.isFull()) {
        return bean;
    }
    Controller controller = AnnotationUtils.findAnnotation(bean.getClass(), Controller.class);
    RestController restController = AnnotationUtils.findAnnotation(bean.getClass(), RestController.class);
    RequestMapping requestMapping = AnnotationUtils.findAnnotation(bean.getClass(), RequestMapping.class);
    if (controller != null || restController != null || requestMapping != null) {
        String contextPath = soulSpringMvcConfig.getContextPath();
        SoulSpringMvcClient clazzAnnotation = AnnotationUtils.findAnnotation(bean.getClass(), SoulSpringMvcClient.class);
        String prePath = "";
        if (Objects.nonNull(clazzAnnotation)) {
            if (clazzAnnotation.path().indexOf("*") > 1) {
                post(buildJsonParams(clazzAnnotation, contextPath, prePath));
                return bean;
            }
            prePath = clazzAnnotation.path();
        }
        final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(bean.getClass());
        for (Method method : methods) {
            SoulSpringMvcClient soulSpringMvcClient = AnnotationUtils.findAnnotation(method, SoulSpringMvcClient.class);
            if (Objects.nonNull(soulSpringMvcClient)) {
                post(buildJsonParams(soulSpringMvcClient, contextPath, prePath));
            }
        }
    }
    return bean;
}
 
Example 23
Source Project: ci-droid   Source File: SwaggerConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Docket productApi() {
    Docket docket = new Docket(DocumentationType.SWAGGER_2)
            .select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build();
    return docket;
}
 
Example 24
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example 25
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example 26
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example 27
private void registerInclude() {
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
    //根据扫描包获取所有的类
    List<String> scanPackages = secretProperties.getScanPackages();
    if (!CollectionUtils.isEmpty(scanPackages)) {
        isScanAllController = false;
        for (String scanPackage : scanPackages) {
            Set<BeanDefinition> beanDefinitions = secretScanner.findCandidateComponents(scanPackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                includeClassList.add(beanDefinition.getBeanClassName());
            }
        }
    }
}
 
Example 28
private void registerExclude() {
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
    //根据扫描包获取所有的类
    List<String> scanPackages = secretProperties.getExcludePackages();
    if (!CollectionUtils.isEmpty(scanPackages)) {
        for (String scanPackage : scanPackages) {
            Set<BeanDefinition> beanDefinitions = secretScanner.findCandidateComponents(scanPackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                excludeClassList.add(beanDefinition.getBeanClassName());
            }
        }
    }
}
 
Example 29
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class clazz = bean.getClass();
    if(clazz.isAnnotationPresent(RestController.class) || clazz.isAnnotationPresent(Controller.class)) {
        Method[] methods = clazz.getDeclaredMethods();
         for (Method method : methods) {
            int modifiers = method.getModifiers();
            if(Modifier.isPublic(modifiers) && method.isAnnotationPresent(DynamicRateLimiter.class)) {
                if(!redisLimiterProperties.isEnableDynamicalConf()) {
                    throw new RuntimeException("Must set spring.redis-limiter.enable-dynamical-conf = true, then you can use DynamicRateLimiter annotation.");
                }
                DynamicRateLimiter dynamicRateLimiter = method.getAnnotation(DynamicRateLimiter.class);
                int permits = dynamicRateLimiter.permits();
                TimeUnit timeUnit = dynamicRateLimiter.timeUnit();
                String path = dynamicRateLimiter.path();
                String baseExp = dynamicRateLimiter.base();
                LimiterConfig config = new LimiterConfig();
                config.setApplicationName(applicationName);
                config.setBaseExp(baseExp);
                config.setPath(path);
                config.setPermits(permits);
                config.setTimeUnit(timeUnit.name());
                config.setControllerName(clazz.getSimpleName());
                config.setMethodName(method.getName());
                String key = clazz.getSimpleName()+":"+method.getName();
                if(configMap.containsKey(key)) {
                    throw new RuntimeException(String.format("Controller %s method %s has conflict.", clazz.getSimpleName(), method.getName()));
                }
                configMap.put(key, config);
            }
        }
    }
    return bean;
}
 
Example 30
Source Project: BlogManagePlatform   Source File: DefaultEndPointPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isRestEndPoint(OperationContext context) {
	if (context.findControllerAnnotation(RestController.class).isPresent()) {
		return true;
	}
	if (context.findAnnotation(ResponseBody.class).isPresent()) {
		return true;
	}
	return false;
}