Java Code Examples for org.springframework.stereotype.Controller

The following examples show how to use org.springframework.stereotype.Controller. 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: RestDoc   Source File: SpringControllerResolver.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public List<Class> getClasses() {
    List<String> packages = _packages;

    var scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));

    var classes = new ArrayList<Class>();
    if (packages == null) packages = Arrays.asList("cn", "com");
    for (var packageName : packages) {
        var beans = scanner.findCandidateComponents(packageName);
        for (var bean : beans) {
            try {
                var className = bean.getBeanClassName();
                Class clazz = Class.forName(className);

                classes.add(clazz);
            } catch (ClassNotFoundException e) {
                _logger.warn("not found class:" + bean.getBeanClassName(), e);
            }
        }
    }
    return classes;
}
 
Example 2
@Test
public void testWithComponentAnnotationOnly() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Service.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertEquals(3, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertTrue(containsBeanClass(candidates, BarComponent.class));
	assertFalse(containsBeanClass(candidates, FooServiceImpl.class));
	assertFalse(containsBeanClass(candidates, StubFooDao.class));
	assertFalse(containsBeanClass(candidates, NamedStubDao.class));
}
 
Example 3
Source Project: spring-analysis-note   Source File: CglibProxyControllerTests.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerClass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setProxyTargetClass(true);
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			Pointcut pointcut = new AnnotationMatchingPointcut(Controller.class);
			DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleTraceInterceptor(true));
			wac.getBeanFactory().registerSingleton("advisor", advisor);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 4
@Test
public void testWithComponentAnnotationOnly() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Service.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertEquals(3, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertTrue(containsBeanClass(candidates, BarComponent.class));
	assertFalse(containsBeanClass(candidates, FooServiceImpl.class));
	assertFalse(containsBeanClass(candidates, StubFooDao.class));
	assertFalse(containsBeanClass(candidates, NamedStubDao.class));
}
 
Example 5
Source Project: java-technology-stack   Source File: CglibProxyControllerTests.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerClass) throws ServletException {
	servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
			DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
			autoProxyCreator.setProxyTargetClass(true);
			autoProxyCreator.setBeanFactory(wac.getBeanFactory());
			wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator);
			Pointcut pointcut = new AnnotationMatchingPointcut(Controller.class);
			DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleTraceInterceptor(true));
			wac.getBeanFactory().registerSingleton("advisor", advisor);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());
}
 
Example 6
Source Project: tephra   Source File: ClassReloaderImpl.java    License: MIT License 6 votes vote down vote up
private String getBeanName(Class<?> clazz) {
    Component component = clazz.getAnnotation(Component.class);
    if (component != null)
        return component.value();

    Repository repository = clazz.getAnnotation(Repository.class);
    if (repository != null)
        return repository.value();

    Service service = clazz.getAnnotation(Service.class);
    if (service != null)
        return service.value();

    Controller controller = clazz.getAnnotation(Controller.class);
    if (controller != null)
        return controller.value();

    return null;
}
 
Example 7
Source Project: zstack   Source File: InventoryIndexManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void populateTriggerVOs() throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(TriggerIndex.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    for (String pkg : getBasePkgNames()) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            Class<?> triggerVO = Class.forName(bd.getBeanClassName());
            if (!triggerVO.isAnnotationPresent(Entity.class)) {
                throw new IllegalArgumentException(String.format("Class[%s] is annotated by @TriggerIndex, but not annotated by @Entity",
                        triggerVO.getName()));
            }
            triggerVOs.add(triggerVO);
            popluateTriggerVONamesCascade(triggerVO);
        }
    }
}
 
Example 8
Source Project: zstack   Source File: ConfigurationManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void generateApiMessageGroovyClass(StringBuilder sb, List<String> basePkgs) {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIMessage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIReply.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                //classToApiMessageGroovyClass(sb, clazz);
                classToApiMessageGroovyInformation(sb, clazz);
            } catch (ClassNotFoundException e) {
                logger.warn(String.format("Unable to generate groovy class for %s", bd.getBeanClassName()), e);
            }
        }
    }
}
 
Example 9
Source Project: zstack   Source File: Deployer.java    License: Apache License 2.0 6 votes vote down vote up
private void scanDeployer() {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(AbstractDeployer.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
    for (BeanDefinition bd : scanner.findCandidateComponents("org.zstack.test")) {
        try {
            Class<?> clazz = Class.forName(bd.getBeanClassName());
            AbstractDeployer d = (AbstractDeployer) clazz.newInstance();
            deployers.put(d.getSupportedDeployerClassType(), d);
            logger.debug(String.format("Scanned a deployer[%s] supporting %s", d.getClass().getName(), d.getSupportedDeployerClassType()));
        } catch (Exception e) {
            logger.warn(String.format("unable to create deployer[%s], it's probably there are some beans requried by deployer is not loaded, skip it. error message:\n%s", bd.getBeanClassName(), e.getMessage()));
        }

    }
}
 
Example 10
@Override
protected Collection<ConfigAttribute> findAttributes(Method method, Class<?> targetClass) {
    Annotation[] annotations = AnnotationUtils.getAnnotations(method);
    List<ConfigAttribute> attributes = new ArrayList<>();

    // if the class is annotated as @Controller we should by default deny access to every method
    if (AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) {
        attributes.add(DENY_ALL_ATTRIBUTE);
    }

    if (annotations != null) {
        for (Annotation a : annotations) {
            // but not if the method has at least a PreAuthorize or PostAuthorize annotation
            if (a instanceof PreAuthorize || a instanceof PostAuthorize) {
                return null;
            }
        }
    }
    return attributes;
}
 
Example 11
private static StaticMethodMatcherPointcut getControllerPointcut() {
	return new StaticMethodMatcherPointcut() {
		@Override
		public boolean matches(Method method, @Nullable Class<?> targetClass) {
			return ((AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) ||
					(AnnotationUtils.findAnnotation(targetClass, RequestMapping.class) != null));
		}
	};
}
 
Example 12
Source Project: spring-analysis-note   Source File: HandlerTypePredicateTests.java    License: MIT License 5 votes vote down vote up
@Test
public void forAnnotation() {

	Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class);

	assertTrue(predicate.test(HtmlController.class));
	assertTrue(predicate.test(ApiController.class));
	assertTrue(predicate.test(AnotherApiController.class));
}
 
Example 13
Source Project: spring-analysis-note   Source File: HandlerTypePredicateTests.java    License: MIT License 5 votes vote down vote up
@Test
public void forAnnotationWithException() {

	Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class)
			.and(HandlerTypePredicate.forAssignableType(Special.class));

	assertFalse(predicate.test(HtmlController.class));
	assertFalse(predicate.test(ApiController.class));
	assertTrue(predicate.test(AnotherApiController.class));
}
 
Example 14
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 15
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 16
Source Project: archunit-examples   Source File: PrimaryAdaptersComponentsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void controllerClassesShouldBeAnnotatedWithControllerOrRestControllerAnnotation() {
  ArchRule rule = ArchRuleDefinition.classes()
    .that().haveSimpleNameEndingWith("Controller")
    .should().beAnnotatedWith(Controller.class)
    .orShould().beAnnotatedWith(RestController.class);
  rule.check(classes);
}
 
Example 17
Source Project: archunit-examples   Source File: PrimaryAdaptersComponentsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void noClassesWithControllerOrRestControllerAnnotationShouldResideOutsideOfPrimaryAdaptersPackages() {
  ArchRule rule = ArchRuleDefinition.noClasses()
    .that().areAnnotatedWith(Controller.class)
    .or().areAnnotatedWith(RestController.class)
    .should().resideOutsideOfPackage(PRIMARY_ADAPTERS_PACKAGES);
  rule.check(classes);
}
 
Example 18
Source Project: archunit-examples   Source File: PrimaryAdaptersComponentsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void publicControllerMethodsShouldBeAnnotatedWithARequestMapping() {
  ArchRule rule = ArchRuleDefinition.methods()
    .that().arePublic()
    .and().areDeclaredInClassesThat().resideInAPackage("..adapters.primary.web..")
    .and().areDeclaredInClassesThat().haveSimpleNameEndingWith("Controller")
    .and().areDeclaredInClassesThat().areAnnotatedWith(Controller.class)
    .or().areDeclaredInClassesThat().areAnnotatedWith(RestController.class)
    .should().beAnnotatedWith(RequestMapping.class)
    .orShould().beAnnotatedWith(GetMapping.class)
    .orShould().beAnnotatedWith(PostMapping.class)
    .orShould().beAnnotatedWith(PatchMapping.class)
    .orShould().beAnnotatedWith(DeleteMapping.class);
  rule.check(classes);
}
 
Example 19
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 20
private static StaticMethodMatcherPointcut getControllerPointcut() {
	return new StaticMethodMatcherPointcut() {
		@Override
		public boolean matches(Method method, @Nullable Class<?> targetClass) {
			return ((AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) ||
					(AnnotationUtils.findAnnotation(targetClass, RequestMapping.class) != null));
		}
	};
}
 
Example 21
Source Project: java-technology-stack   Source File: HandlerTypePredicateTests.java    License: MIT License 5 votes vote down vote up
@Test
public void forAnnotation() {

	Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class);

	assertTrue(predicate.test(HtmlController.class));
	assertTrue(predicate.test(ApiController.class));
	assertTrue(predicate.test(AnotherApiController.class));
}
 
Example 22
Source Project: java-technology-stack   Source File: HandlerTypePredicateTests.java    License: MIT License 5 votes vote down vote up
@Test
public void forAnnotationWithException() {

	Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class)
			.and(HandlerTypePredicate.forAssignableType(Special.class));

	assertFalse(predicate.test(HtmlController.class));
	assertFalse(predicate.test(ApiController.class));
	assertTrue(predicate.test(AnotherApiController.class));
}
 
Example 23
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 24
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 25
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 26
@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 27
Source Project: BlogManagePlatform   Source File: AOPUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断该类是否为Controller
 * @author Frodez
 * @date 2020-01-01
 */
public static boolean isController(Class<?> klass) {
	if (AnnotationUtils.findAnnotation(klass, Controller.class) != null) {
		return true;
	}
	if (AnnotationUtils.findAnnotation(klass, RestController.class) != null) {
		return true;
	}
	return false;
}
 
Example 28
Source Project: fileServer   Source File: SwaggerConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Docket createRestApi() {
    Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
        @Override
        public boolean apply(RequestHandler input) {
            Class<?> declaringClass = input.declaringClass();

            boolean isController = declaringClass.isAnnotationPresent(Controller.class);
            boolean isRestController = declaringClass.isAnnotationPresent(RestController.class);

            String className = declaringClass.getName();

            String pattern = "com\\.codingapi\\.file\\.fastdfs\\.server\\.controller\\..*Controller";
            boolean has =  Pattern.matches(pattern, className);
            if(has){
                if(isController){
                    if(input.isAnnotatedWith(ResponseBody.class)){
                        return true;
                    }
                }
                if(isRestController){
                    return true;
                }
                return false;
            }

            return false;
        }
    };
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .useDefaultResponseMessages(false)
            .select()
            .apis(predicate)
            .build();
}
 
Example 29
Source Project: fileServer   Source File: SwaggerConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Docket createRestApi() {
    Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
        @Override
        public boolean apply(RequestHandler input) {
            Class<?> declaringClass = input.declaringClass();

            boolean isController = declaringClass.isAnnotationPresent(Controller.class);
            boolean isRestController = declaringClass.isAnnotationPresent(RestController.class);

            String className = declaringClass.getName();

            String pattern = "com\\.codingapi\\.file\\.local\\.server\\.controller\\..*Controller";
            boolean has =  Pattern.matches(pattern, className);
            if(has){
                if(isController){
                    if(input.isAnnotatedWith(ResponseBody.class)){
                        return true;
                    }
                }
                if(isRestController){
                    return true;
                }
                return false;
            }

            return false;
        }
    };
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .useDefaultResponseMessages(false)
            .select()
            .apis(predicate)
            .build();
}
 
Example 30
Source Project: hsweb-framework   Source File: AopAuthorizingController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(Method method, Class<?> aClass) {
    boolean support = AopUtils.findAnnotation(aClass, Controller.class) != null
            || AopUtils.findAnnotation(aClass, RestController.class) != null
            || AopUtils.findAnnotation(aClass, method, Authorize.class) != null;

    if (support && autoParse) {
        defaultParser.parse(aClass, method);
    }
    return support;
}