org.springframework.stereotype.Controller Java Examples

The following examples show how to use org.springframework.stereotype.Controller. 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: ClassPathScanningCandidateComponentProviderTests.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@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 #2
Source File: SpringControllerResolver.java    From RestDoc with 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 #3
Source File: ClassReloaderImpl.java    From tephra with 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 #4
Source File: ClassPathScanningCandidateComponentProviderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 File: Deployer.java    From zstack with 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 #6
Source File: InventoryIndexManagerImpl.java    From zstack with 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 #7
Source File: CglibProxyControllerTests.java    From java-technology-stack with 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 #8
Source File: ConfigurationManagerImpl.java    From zstack with 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 File: CglibProxyControllerTests.java    From spring-analysis-note with 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 #10
Source File: CustomPermissionAllowedMethodSecurityMetadataSource.java    From tutorials with MIT License 6 votes vote down vote up
@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
Source File: HandlerTypePredicateTests.java    From java-technology-stack with 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 #12
Source File: OpenAPIBuilder.java    From springdoc-openapi with 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 #13
Source File: SpringCodingRulesTest.java    From archunit-examples with 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 #14
Source File: SpringMvcClientBeanPostProcessor.java    From soul with 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 #15
Source File: EnforceAuthorizationLogicsUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static void testIfControllerClassHasProperAnnotation() {
    Set<Class<?>> apiClasses = REFLECTIONS.getTypesAnnotatedWith(Path.class);
    Set<String> controllersClasses = Sets.newHashSet();
    apiClasses.stream().forEach(apiClass -> controllersClasses.addAll(
            REFLECTIONS.getSubTypesOf((Class<Object>) apiClass).stream().map(Class::getSimpleName).collect(Collectors.toSet())));
    Set<String> classesWithControllerAnnotation = REFLECTIONS.getTypesAnnotatedWith(Controller.class)
            .stream().map(Class::getSimpleName).collect(Collectors.toSet());
    Set<String> controllersWithoutAnnotation = Sets.difference(controllersClasses, classesWithControllerAnnotation);

    assertTrue("These classes are missing @Controller annotation: " + Joiner.on(",").join(controllersWithoutAnnotation),
            controllersWithoutAnnotation.isEmpty());
}
 
Example #16
Source File: HandlerTypePredicateTests.java    From java-technology-stack with 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 #17
Source File: ConfigurationManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void handle(APIGenerateSqlVOViewMsg msg) {
    try {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
        scanner.addIncludeFilter(new AnnotationTypeFilter(EO.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
        StringBuilder sb = new StringBuilder();
        for (String pkg : msg.getBasePackageNames()) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                Class<?> entityClazz = Class.forName(bd.getBeanClassName());
                generateVOViewSql(sb, entityClazz);
            }
        }

        String exportPath = PathUtil.join(System.getProperty("user.home"), "zstack-mysql-view");
        FileUtils.deleteDirectory(new File(exportPath));
        File folder = new File(exportPath);
        folder.mkdirs();
        File outfile = new File(PathUtil.join(exportPath, "view.sql"));
        FileUtils.writeStringToFile(outfile, sb.toString());

        APIGenerateSqlVOViewEvent evt = new APIGenerateSqlVOViewEvent(msg.getId());
        bus.publish(evt);
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #18
Source File: HandlerMethodAnnotationDetectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 #19
Source File: SecretRequestAdvice.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: SecretRequestAdvice.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: InventoryIndexManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void populateInventoryIndexer() throws URISyntaxException, ClassNotFoundException, NoSuchMethodException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Inventory.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    for (String pkg : getBasePkgNames()) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            Class<?> inventoryClass = Class.forName(bd.getBeanClassName());
            Inventory invat = inventoryClass.getAnnotation(Inventory.class);
            if (!triggerVOs.contains(invat.mappingVOClass())) {
                String err = String.format("Inventory[%s]'s mapping VO class[%s] is not annotated by @TriggerIndex", inventoryClass.getName(), invat
                        .mappingVOClass().getName());
                throw new IllegalArgumentException(err);
            }

            String mappingClassSimpleName = invat.mappingVOClass().getSimpleName();
            IndexerInfo info = voClassToIndexerMapping.get(mappingClassSimpleName);
            if (info == null) {
                String invName = inventoryClass.getSimpleName();
                info = new IndexerInfo();
                info.url = String.format("%s/%s/%s", elasticSearchBaseUrl, invName.toLowerCase(), invName);
                info.inventoryClass = inventoryClass;
                info.inventoryName = invName;
                info.mappingVOClass = invat.mappingVOClass();
                info.valueOfMethod = getValueOfMethodOfInventoryClass(inventoryClass);
                info.entityIdField = getEntityIdFieldFromClass(info.mappingVOClass);
                info.entityIdField.setAccessible(true);
                voClassToIndexerMapping.put(mappingClassSimpleName, info);
            }
        }
    }
}
 
Example #22
Source File: AOPUtil.java    From BlogManagePlatform with 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 #23
Source File: InventoryQueryDetailsGenerator.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static void generate(String exportPath, List<String> basePkgs) {
    try {
        if (exportPath == null) {
            exportPath = PathUtil.join(System.getProperty("user.home"), "zstack-inventory-query-details");
        }

        if (basePkgs == null || basePkgs.isEmpty()) {
            basePkgs = new ArrayList<String>(1);
            basePkgs.add("org.zstack");
        }

        FileUtils.deleteDirectory(new File(exportPath));
        File folder = new File(exportPath);
        folder.mkdirs();

        String folderName = folder.getAbsolutePath();
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Inventory.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
        for (String pkg : basePkgs) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                generateInventoryDetails(folderName, clazz);
            }
        }
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #24
Source File: SwaggerConfig.java    From fileServer with 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 #25
Source File: SwaggerConfig.java    From fileServer with 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 #26
Source File: AopAuthorizingController.java    From hsweb-framework with 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;
}
 
Example #27
Source File: JavaMelodyAutoConfiguration.java    From cat-boot with Apache License 2.0 5 votes vote down vote up
@ConditionalOnProperty(name = "javamelody.enableSpringControllerMonitoring", havingValue = "true")
@Bean
public MonitoringSpringAdvisor springControllerMonitoringAdvisor() {
    final MonitoringSpringAdvisor interceptor = new MonitoringSpringAdvisor();
    interceptor.setPointcut(new AnnotationMatchingPointcut(Controller.class));
    return interceptor;
}
 
Example #28
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 #29
Source File: ClassPathScanningCandidateComponentProviderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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(2, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertFalse(containsBeanClass(candidates, FooServiceImpl.class));
	assertFalse(containsBeanClass(candidates, StubFooDao.class));
	assertFalse(containsBeanClass(candidates, NamedStubDao.class));
}
 
Example #30
Source File: HandlerMethodAnnotationDetectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static StaticMethodMatcherPointcut getControllerPointcut() {
	return new StaticMethodMatcherPointcut() {
		@Override
		public boolean matches(Method method, Class<?> targetClass) {
			return ((AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) ||
					(AnnotationUtils.findAnnotation(targetClass, RequestMapping.class) != null));
		}
	};
}