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; }
public void start() { ResteasyDeployment dp = new ResteasyDeployment(); Collection<Object> providers = ac.getBeansWithAnnotation(Provider.class).values(); Collection<Object> controllers = ac.getBeansWithAnnotation(Controller.class).values(); Assert.notEmpty(controllers); // extract providers if (providers != null) { dp.getProviders().addAll(providers); } // extract only controller annotated beans dp.getResources().addAll(controllers); netty = new NettyJaxrsServer(); netty.setDeployment(dp); netty.setIoWorkerCount(ioWorkerCount); netty.setExecutorThreadCount(executorThreadCount); netty.setPort(port); netty.setRootResourcePath(rootResourcePath); netty.setSecurityDomain(null); netty.start(); LOGGER.info("rest-netty-server started , port {}", port); }
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); } } }
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); } } } }
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())); } } }
@Override public boolean start() { try { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter(new AnnotationTypeFilter(Inventory.class)); scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class)); scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class)); for (String pkg : getBasePkgNames()) { for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) { Class<?> inventoryClass = Class.forName(bd.getBeanClassName()); Inventory invat = inventoryClass.getAnnotation(Inventory.class); Info info = new Info(); info.inventory = invat; info.inventoryClass = inventoryClass; inventoryMapping.put(invat.mappingVOClass(), info); } } } catch (Exception e) { throw new CloudRuntimeException(e); } return true; }
@RequestMapping("/ConventerServlet") @ResponseBody String Controller(@RequestParam("jsonData") JSONObject data) { JSONObject sendObject = new JSONObject(); String requestValue = ""; try { requestValue = data.getString("operationCall"); } catch (JSONException e) { e.printStackTrace(); } sendObject = setNewRateToJsonObject(requestValue); return sendObject.toString(); }
public void execute() throws MojoExecutionException, MojoFailureException { try { outputtFolder = new File(new File(sourceDocFolder), "restapi"); outputtFolder.mkdirs(); setupClasspath(); setupHandlerbars(); reflections = new Reflections(packageName); apiDescriptionsFinder = new ApiDescriptionFinder(); Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class); for (Class<?> controller : controllers) { getLog().info("Found Controller: " + controller.getName()); processRestApiController(controller); } fillModelFields(); SortedSet<ApiObjectDoc> sortedObjects = new TreeSet<ApiObjectDoc>(modelObjects); generateFile(sortedObjects, "api_models", "models"); } catch (Exception e) { throw new MojoExecutionException("Failed", e); } }
private String getBeanName(final Class<?> clazz) { final Component componentAnno = clazz.getAnnotation(Component.class); if(componentAnno != null && !componentAnno.value().isEmpty()) { return componentAnno.value(); } final Service serviceAnno = clazz.getAnnotation(Service.class); if(serviceAnno != null && !serviceAnno.value().isEmpty()) { return serviceAnno.value(); } final Repository repositoryAnno = clazz.getAnnotation(Repository.class); if(repositoryAnno != null && !repositoryAnno.value().isEmpty()) { return repositoryAnno.value(); } final Controller controllerAnno = clazz.getAnnotation(Controller.class); if(controllerAnno != null && !controllerAnno.value().isEmpty()) { return controllerAnno.value(); } // ステレオタイプのアノテーションでBean名の指定がない場合は、クラス名の先頭を小文字にした名称とする。 return uncapitalize(clazz.getSimpleName()); }
@Override public void process(RoundEnvironment roundEnv) { Set<TypeElement> annotatedTypes = ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith( annotationType())); Iterable<TypeElement> controllerTypes = filterByAnnotation( annotatedTypes, Controller.class ); for (TypeElement controller : controllerTypes) { Iterable<ExecutableElement> requestMethods = filterByAnnotation( ElementFilter.methodsIn(controller.getEnclosedElements()), RequestMapping.class ); processTypeAndMethods(controller, requestMethods); } }
private Annotation getSpringClassAnnotation(Class clazz) { Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class); if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, RestController.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class); } return classAnnotation; }
protected String[] determineUrlsByAnnotations(Object handler) { Class<? extends Object> handlerType = handler.getClass(); RequestMapping mapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (mapping != null) { // @RequestMapping found at type level this.cachedMappings.put(handlerType, mapping); Set<String> urls = new LinkedHashSet<String>(); String[] paths = mapping.value(); if (paths.length > 0) { // @RequestMapping specifies paths at type level for (String path : paths) { addUrlsForPath(urls, path); } return StringUtils.toStringArray(urls); } else { // actual paths specified by @RequestMapping at method level return determineUrlsForHandlerMethods(handlerType); } } else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) { // @RequestMapping to be introspected at method level return determineUrlsForHandlerMethods(handlerType); } else { return null; } }
private void init(ApplicationContext context) { init(); LOGGER.debug("Get All ExceptionHandlers"); List<Object> exceptionsHandlers = ReflectionUtils .proxyToObject(context.getBeansWithAnnotation(ControllerAdvice.class).values()); LOGGER.debug("Get All RestController"); exceptionsHandlers.forEach(this::buildHttpCodes); controllers .addAll(ReflectionUtils.proxyToObject(context.getBeansWithAnnotation(RestController.class).values())); LOGGER.debug("Get All Controller"); controllers.addAll(ReflectionUtils.proxyToObject(context.getBeansWithAnnotation(Controller.class).values())); }
@Nullable @Override public <T> AnnotatedComponent<T> process(Scope scope, Class<T> clazz) { Controller controller = clazz.getAnnotation(Controller.class); if (controller != null) { return new AnnotatedComponent(clazz, controller.value(), ComponentType.CONTROLLER); } Service service = clazz.getAnnotation(Service.class); if (service != null) { return new AnnotatedComponent(clazz, service.value(), ComponentType.CONTROLLER); } return null; }
/** * 判断整个类里的所有接口是否都返回json * * @param classz * @return */ protected boolean isJson(Class<?> classz) { Controller controllerAnno = classz.getAnnotation(Controller.class); RestController restControllerAnno = classz.getAnnotation(RestController.class); ResponseBody responseBody = classz.getAnnotation(ResponseBody.class); if (responseBody != null) { return true; } else if (controllerAnno != null) { return false; } else if (restControllerAnno != null) { return true; } return false; }
@Override public boolean filter(Class<?> classz) { if (classz.getAnnotation(RequestMapping.class) != null || classz.getAnnotation(Controller.class) != null || classz.getAnnotation(RestController.class) != null) { return true; } return false; }
public DwrClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { super(registry, false); addExcludeFilter(new AnnotationTypeFilter(Component.class)); addExcludeFilter(new AnnotationTypeFilter(Service.class)); addExcludeFilter(new AnnotationTypeFilter(Repository.class)); addExcludeFilter(new AnnotationTypeFilter(Controller.class)); setScopedProxyMode(ScopedProxyMode.INTERFACES); }
@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; }
/** * 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); } } }
@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)); }
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)); } }; }
@ConditionalOnProperty(name = "javamelody.enableSpringControllerMonitoring", havingValue = "true") @Bean public MonitoringSpringAdvisor springControllerMonitoringAdvisor() { final MonitoringSpringAdvisor interceptor = new MonitoringSpringAdvisor(); interceptor.setPointcut(new AnnotationMatchingPointcut(Controller.class)); return interceptor; }
public void start() { ResteasyDeployment dp = new ResteasyDeployment(); Collection<Object> providers = ac.getBeansWithAnnotation(Provider.class).values(); Collection<Object> controllers = ac.getBeansWithAnnotation(Controller.class).values(); Assert.notEmpty(controllers); // extract providers if (providers != null) { dp.getProviders().addAll(providers); } // extract only controller annotated beans dp.getResources().addAll(controllers); Map<String, Object> channelOptions = new HashMap<String, Object>(); channelOptions.put("reuseAddress", true); List<ChannelHandler> channelHandlerList = new ArrayList<ChannelHandler>(); channelHandlerList.add(channelHandler); channelHandlerList.add(idleStateHandler); channelHandlerList.add(healthCheckHandler); netty = new NettyJaxrsServer(); netty.setChannelOptions(channelOptions); netty.setDeployment(dp); netty.setPort(port); netty.setRootResourcePath("/resteasy"); netty.setIoWorkerCount(ioWorkerCount); netty.setExecutorThreadCount(executorThreadCount); netty.setMaxRequestSize(maxRequestSize); netty.setSSLContext(sslContext); netty.setKeepAlive(true); netty.setChannelHandlers(channelHandlerList); netty.setSecurityDomain(null); netty.start(); }
private String getTargetType(MethodInvocation methodInvocation) { Class<?> targetType = methodInvocation.getThis().getClass(); if (hasAnnotation(targetType, Controller.class)) { return "Controller"; } else if (hasAnnotation(targetType, Service.class)) { return "Service"; } else if (hasAnnotation(targetType, Repository.class)) { return "Repository"; } else { return "Trace"; } }
@Override protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { String name = invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName(); StopWatch stopWatch = new StopWatch(name); Object returnValue = null; boolean exitThroughException = false; try { stopWatch.start(name); writeStartLog(replacePlaceholders(enterMessage, invocation, null, null, -1)); returnValue = invocation.proceed(); return returnValue; } catch (Throwable ex) { if (stopWatch.isRunning()) { stopWatch.stop(); } exitThroughException = true; //만약 컨트롤러면 예외를 강제로 지정한다. 컨트롤러에서 발생한 예외가 필터까지 오지 못하는 상황을 방지한다. if (hasAnnotation(invocation.getThis().getClass(), Controller.class)) { traceLogManager.setException(ex); } writeExceptionLog(replacePlaceholders(exceptionMessage, invocation, null, ex, stopWatch.getTotalTimeMillis()), ex); throw ex; } finally { if (!exitThroughException) { if (stopWatch.isRunning()) { stopWatch.stop(); } writeEndLog(replacePlaceholders(exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis())); } } }
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); } }
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); } } } }
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); } }
@Override public JAnnotationUse apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) { Class<? extends Annotation> annotationType; switch (springVersion) { case 3 : annotationType = Controller.class; break; case 4 : annotationType = RestController.class; break; default: throw new IllegalStateException("Spring Version not set"); } return generatableType.annotate(annotationType); }
private Set<Class<?>> getAllRestfulControllerClasses() { String packageToSearchForControllers = config.getPackageToSearchForControllers(); if (StringUtils.isBlank(packageToSearchForControllers)) { throw new RuntimeException("Please provide package to search for controllers in configuration"); } log.debug("Looking up on package " + packageToSearchForControllers); Set<Class<?>> controllerSet = new Reflections(packageToSearchForControllers).getTypesAnnotatedWith(Controller.class); log.debug("Spring controllers found : " + controllerSet.size()); Set<Class<?>> restcontrollersSet = new Reflections(packageToSearchForControllers).getTypesAnnotatedWith(RestController.class); log.debug("Spring restcontrollers found : " + restcontrollersSet.size()); controllerSet.addAll(restcontrollersSet); log.debug("Found Controllers: " + StringUtils.join(controllerSet, ", ")); return controllerSet; }
private Annotation getSpringClassAnnotation(Class clazz){ Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class); if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class); } return classAnnotation; }
private List<APIInfo> getApiInfos() { List<APIInfo> apiInfos = new ArrayList<>(); Collection<Object> controllers = applicationContext.getBeansWithAnnotation(Controller.class).values(); controllers.forEach(controller -> { APIInfo apiInfo = new APIInfo( cleanProxiedClassName(controller.getClass()), getAPIName(controller.getClass()) ); // Root request mapping RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(controller.getClass(), RequestMapping.class); // Gets all the methods ReflectionUtils.doWithMethods( controller.getClass(), method -> { RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (methodAnnotation != null) { APIMethodInfo apiMethodInfo = collectAPIMethodInfo( apiInfo, method, typeAnnotation, methodAnnotation ); apiInfo.add(apiMethodInfo); } }, ReflectionUtils.USER_DECLARED_METHODS ); // OK for this API apiInfos.add(apiInfo); }); return apiInfos; }
public void scan(ApplicationContext applicationContext) { Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(Controller.class); if (null == controllers || controllers.isEmpty()) { throw new IllegalArgException("No @Controllers found in Spring context."); } configureMappings(applicationContext.getBean(DefaultController.class), DefaultController.class); controllers.values().forEach(bean -> configureMappings(bean, bean.getClass())); logMappingInfo(); }
protected String getActionName(){ String action=this.getClass().getSimpleName(); Controller ac=this.getClass().getAnnotation(Controller.class); if(ac!=null){ action=ac.value(); if(action.lastIndexOf("Action")>0)action=action.substring(0,action.lastIndexOf("Action")); } return action; }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod hm=(HandlerMethod)handler; Method method=hm.getMethod(); //don't need to do anything if it's not a controller class if(!method.getDeclaringClass().isAnnotationPresent(Controller.class)) { return true; } //if trying to access an admin path but admin tool is disabled, redirect to home Boolean blAdminToolEnabled = (adminToolEnabled!=null && adminToolEnabled.equals("true")) ? true : false; LOG.debug("Admin tool enabled status is {}", blAdminToolEnabled); if (request.getServletPath().contains("/admin") && !blAdminToolEnabled) { response.sendRedirect(request.getContextPath() + HOMEPAGE_PATH); return false; } if (method.isAnnotationPresent(LoginRequired.class) || method.isAnnotationPresent(AdminLoginRequired.class)) { Boolean adminLoggedIn = (Boolean) request.getSession().getAttribute(Constants.ADMIN_LOGGEDIN_SESSATTRIB); adminLoggedIn = (adminLoggedIn==null) ? false : adminLoggedIn; LOG.debug("Admin logged in status is {}", adminLoggedIn); if(method.isAnnotationPresent(LoginRequired.class)) { //these are all of the cases in which you would not go to the requested page, but instead be redirected somewhere else. User user = (User) request.getSession().getAttribute(USER_SESSION_ATTRIBUTE); //The LoginRequired annotation is on all user management pages. If admin is logged in but no user is loaded, redirect to users list to pick one if (adminLoggedIn && user==null) { response.sendRedirect(request.getContextPath() + ADMIN_USERS_PATH); return false; } if (!adminLoggedIn) { //if admin user isn't logged in and no oauth account is loaded redirect to oauth login OAuthProviderAccount account = (OAuthProviderAccount) request.getSession().getAttribute(ACCOUNT_SESSION_ATTRIBUTE); if(account == null) { response.sendRedirect(request.getContextPath() + USER_LOGIN_PATH); return false; } //if admin user isn't logged in and there is an oauth account signed in, but no user to go with it, redirect to the sign up form if((!method.getName().equals(SIGNUPFORM_METHOD) &&!method.getName().equals(ADDUSER_METHOD)) && (user == null || user.getUserId()==0)) { //new user, get them signed up! response.sendRedirect(request.getContextPath() + USER_SIGNUP_PATH); return false; } } } else if (method.isAnnotationPresent(AdminLoginRequired.class)) { if (!adminLoggedIn) { response.sendRedirect(request.getContextPath() + ADMIN_LOGIN_PATH); return false; } } } return true; }
@Override protected boolean isHandler(Class<?> beanType) { return (AnnotationUtils.findAnnotation(beanType, Controller.class) != null); }
/** * Checks for presence of the {@link org.springframework.web.bind.annotation.RequestMapping} * annotation on the handler class and on any of its methods. */ @Override protected String[] determineUrlsForHandler(String beanName) { ApplicationContext context = getApplicationContext(); Class<?> handlerType = context.getType(beanName); RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); if (mapping != null) { // @RequestMapping found at type level this.cachedMappings.put(handlerType, mapping); Set<String> urls = new LinkedHashSet<String>(); String[] typeLevelPatterns = mapping.value(); if (typeLevelPatterns.length > 0) { // @RequestMapping specifies paths at type level String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType, true); for (String typeLevelPattern : typeLevelPatterns) { if (!typeLevelPattern.startsWith("/")) { typeLevelPattern = "/" + typeLevelPattern; } boolean hasEmptyMethodLevelMappings = false; for (String methodLevelPattern : methodLevelPatterns) { if (methodLevelPattern == null) { hasEmptyMethodLevelMappings = true; } else { String combinedPattern = getPathMatcher().combine(typeLevelPattern, methodLevelPattern); addUrlsForPath(urls, combinedPattern); } } if (hasEmptyMethodLevelMappings || org.springframework.web.servlet.mvc.Controller.class.isAssignableFrom(handlerType)) { addUrlsForPath(urls, typeLevelPattern); } } return StringUtils.toStringArray(urls); } else { // actual paths specified by @RequestMapping at method level return determineUrlsForHandlerMethods(handlerType, false); } } else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) { // @RequestMapping to be introspected at method level return determineUrlsForHandlerMethods(handlerType, false); } else { return null; } }