Example usage for org.springframework.context ApplicationContext getType

List of usage examples for org.springframework.context ApplicationContext getType

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getType.

Prototype

@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;

Source Link

Document

Determine the type of the bean with the given name.

Usage

From source file:org.vaadin.addons.springsecurityviewprovider.SpringSecurityViewProvider.java

@SuppressWarnings("unchecked")
public final static ViewProvider createViewProvider(final Authentication authentication,
        Boolean enableCaching) {/* ww w.j  a v a 2  s  . c o  m*/
    final SpringSecurityViewProvider springViewProvider = new SpringSecurityViewProvider();
    springViewProvider.enableCaching = enableCaching;

    try {
        final ApplicationContext applicationContext = springViewProvider.applicationContext;

        // Retrieve the default SecurityExpressionHandler 
        final MethodSecurityExpressionHandler securityExpressionHandler = applicationContext
                .getBean(DefaultMethodSecurityExpressionHandler.class);
        // The method that is protected in the end
        final Method getViewMethod = SpringSecurityViewProvider.class.getMethod("getView", String.class);
        // A parser to evaluate parse the permissions.
        final SpelExpressionParser parser = new SpelExpressionParser();

        // Although beans can be retrieved by annotation they must be retrieved by name
        // to avoid instanciating them
        for (String beanName : applicationContext.getBeanDefinitionNames()) {
            final Class<?> beanClass = applicationContext.getType(beanName);
            // only work with Views that are described by our specialed Description
            if (beanClass.isAnnotationPresent(ViewDescription.class)
                    && View.class.isAssignableFrom(beanClass)) {
                final ViewDescription viewDescription = beanClass.getAnnotation(ViewDescription.class);
                // requires no special permissions and can be immediatly added
                if (StringUtils.isBlank(viewDescription.requiredPermissions())) {
                    springViewProvider.views.put(viewDescription.name(), (Class<? extends View>) beanClass);
                }
                // requires permissions
                else {
                    // this is actually borrowed from the code in org.springframework.security.access.prepost.PreAuthorize
                    final EvaluationContext evaluationContext = securityExpressionHandler
                            .createEvaluationContext(authentication, new SimpleMethodInvocation(
                                    springViewProvider, getViewMethod, viewDescription.name()));
                    // only add the view to my provider if the permissions evaluate to true                  
                    if (ExpressionUtils.evaluateAsBoolean(
                            parser.parseExpression(viewDescription.requiredPermissions()), evaluationContext))
                        springViewProvider.views.put(viewDescription.name(), (Class<? extends View>) beanClass);
                }
            }
        }
    } catch (NoSuchMethodException | SecurityException e) {
        // Won't happen
    }

    return springViewProvider;
}

From source file:com.graby.store.base.remote.RemotingAnnotationHandlerMapping.java

/**
 * Checks for presence of the {@link org.springframework.web.bind.annotation.RequestMapping}
 * annotation on the handler class and on any of its methods.
 *///from   ww  w .  ja  va  2  s .  co  m
protected String[] determineUrlsForHandler(String beanName) {

    ApplicationContext context = getApplicationContext();
    Class<?> handlerType = context.getType(beanName);
    RemotingService mapping = AnnotationUtils.findAnnotation(handlerType, RemotingService.class);
    if (mapping == null && context instanceof ConfigurableApplicationContext
            && context.containsBeanDefinition(beanName)) {
        ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;
        BeanDefinition bd = cac.getBeanFactory().getMergedBeanDefinition(beanName);
        if (bd instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
            if (abd.hasBeanClass()) {
                Class<?> beanClass = abd.getBeanClass();
                mapping = AnnotationUtils.findAnnotation(beanClass, RemotingService.class);
            }
        }
    }

    if (mapping != null) {
        this.cachedMappings.put(handlerType, mapping);
        Set<String> urls = new LinkedHashSet<String>();
        String path = mapping.serviceUrl();
        if (path != null) {
            addUrlsForPath(urls, path);
            return StringUtils.toStringArray(urls);
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.freebox.engeneering.application.web.common.ApplicationUIProvider.java

@SuppressWarnings("unchecked")
@Override//from   w  ww  .  j  a  v  a 2s . co  m
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
    VaadinRequest request = event.getRequest();

    Object uiBeanNameObj = request.getService().getDeploymentConfiguration()
            .getApplicationOrSystemProperty("UIBean", null);

    if (uiBeanNameObj instanceof String) {
        String uiBeanName = uiBeanNameObj.toString();
        final ApplicationContext applicationContext = ApplicationContextLocator.getApplicationContext();
        final Class<? extends UI> bean = (Class<? extends UI>) applicationContext.getType(uiBeanName);
        if (bean != null) {
            return bean;
        } else {
            ClassLoader classLoader = request.getService().getClassLoader();
            try {
                Class<? extends UI> uiClass = Class.forName(uiBeanName, true, classLoader).asSubclass(UI.class);

                return uiClass;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Could not find UI class", e);
            }
        }
    }
    return null;
}

From source file:br.com.caelum.vraptor.ioc.spring.StereotypedBeansRegistrar.java

private void handleRefresh(ApplicationContext beanFactory) {
    String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (String name : beanDefinitionNames) {
        Class<?> beanType = beanFactory.getType(name);
        LOGGER.debug("scanning {} for bean definition {}", beanType, name);
        if (beanType == null) {
            LOGGER.info("null type for bean {}", name);
            continue;
        }/*from ww w.j  av  a2 s .c  o  m*/

        for (StereotypeHandler handler : stereotypeHandlers) {
            LOGGER.trace("scanning {} with {}", beanType, handler);
            if (beanType.isAnnotationPresent(handler.stereotype())) {
                handler.handle(beanType);
            }
        }
    }
}

From source file:com.fortuityframework.spring.broker.SpringEventListenerLocator.java

/**
 * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
 *///  ww w .j  av a2s. c o  m
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextStartedEvent || event instanceof ContextRefreshedEvent) {
        ApplicationContext context = ((ApplicationContextEvent) event).getApplicationContext();

        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            Class<?> type = context.getType(beanDefinitionName);

            if (type != null && type.getMethods() != null) {
                for (Method m : type.getMethods()) {
                    registerMethodAsListener(context, beanDefinitionName, m);
                }
            }
        }
    }

}

From source file:ch.ralscha.extdirectspring.controller.MethodRegistrar.java

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

    ApplicationContext context = (ApplicationContext) event.getSource();

    String[] beanNames = context.getBeanNamesForType(Object.class);

    for (String beanName : beanNames) {

        Class<?> handlerType = context.getType(beanName);
        final Class<?> userType = ClassUtils.getUserClass(handlerType);

        Set<Method> methods = MethodIntrospector.selectMethods(userType, new MethodFilter() {
            @Override//from ww w  . jav  a 2s .  co m
            public boolean matches(Method method) {
                return AnnotationUtils.findAnnotation(method, ExtDirectMethod.class) != null;
            }
        });

        for (Method method : methods) {
            ExtDirectMethod directMethodAnnotation = AnnotationUtils.findAnnotation(method,
                    ExtDirectMethod.class);
            final String beanAndMethodName = beanName + "." + method.getName();
            if (directMethodAnnotation.value().isValid(beanAndMethodName, userType, method)) {
                this.methodInfoCache.put(beanName, handlerType, method, event.getApplicationContext());

                // /CLOVER:OFF
                if (log.isDebugEnabled()) {
                    String info = "Register " + beanAndMethodName + "(" + directMethodAnnotation.value();
                    if (StringUtils.hasText(directMethodAnnotation.group())) {
                        info += ", " + directMethodAnnotation.group();
                    }
                    info += ")";
                    log.debug(info);
                }
                // /CLOVER:ON
            }
        }

    }
}

From source file:net.bull.javamelody.TestMonitoringSpringInterceptor.java

/** Test. */
@Test//  ww  w .jav  a2 s .  c o m
public void testSpringDataSourceFactoryBean() {
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME, });
    // utilisation de l'InvocationHandler dans SpringDataSourceFactoryBean
    context.getType("wrappedDataSource");
    context.getBean("wrappedDataSource");

    try {
        new SpringDataSourceFactoryBean().createInstance();
    } catch (final IllegalStateException e) {
        assertNotNull("ok", e);
    }
}

From source file:net.bull.javamelody.TestMonitoringSpringInterceptor.java

/** Test. */
@Test//w w  w. j  ava 2s.c o m
public void testSpringDataSourceBeanPostProcessor() {
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME, });
    // utilisation de l'InvocationHandler dans SpringDataSourceBeanPostProcessor
    context.getType("dataSource2");
    context.getBean("dataSource2");

    Utils.setProperty(Parameter.NO_DATABASE, "true");
    assertNotNull("no database context", new ClassPathXmlApplicationContext(
            new String[] { MONITORING_CONTEXT_FILENAME, TEST_CONTEXT_FILENAME, }));
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

@Override
protected Set<Class> findActions() {
    Set<Class> classes = new HashSet<Class>();

    final ApplicationContext ac = this.applicationContext;
    String[] beanNames = ac.getBeanDefinitionNames();
    for (String beanName : beanNames) {

        // don't care for the bean itself right now, just it's class
        Class beanClass = ac.getType(beanName);

        // first of all, check for the @Controller annotation...
        // then, if it's inside the right package (base controllers package)
        if (beanClass.isAnnotationPresent(Controller.class)
                && beanClass.getPackage().getName().startsWith(this.packageLocatorsBasePackage)) {
            // we must warn in case of a singleton scoped controller
            if (ac.isSingleton(beanName)) {
                LOG.warn(""); // TODO
            }/*from  w  w w  .  j  a  v  a 2s. c om*/
            classes.add(beanClass);
        }

    }
    return classes;
}