Example usage for org.springframework.web.context WebApplicationContext getBeansOfType

List of usage examples for org.springframework.web.context WebApplicationContext getBeansOfType

Introduction

In this page you can find the example usage for org.springframework.web.context WebApplicationContext getBeansOfType.

Prototype

<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

Source Link

Document

Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

/**
 * Collects all PropertyEditorRegistrars in the application context and
 * calls them to register their custom editors
 *
 * @param servletContext/* w ww  . ja v  a  2 s. co  m*/
 * @param registry The PropertyEditorRegistry instance
 */
private static void registerCustomEditors(ServletContext servletContext, PropertyEditorRegistry registry) {
    if (servletContext == null) {
        return;
    }

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    if (context == null) {
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, PropertyEditorRegistrar> editors = (Map<String, PropertyEditorRegistrar>) servletContext
            .getAttribute(PROPERTY_EDITOR_REGISTRARS);
    if (editors == null) {
        editors = context.getBeansOfType(PropertyEditorRegistrar.class);
        if (!Environment.isDevelopmentMode()) {
            servletContext.setAttribute(PROPERTY_EDITOR_REGISTRARS, editors);
        }
    }
    for (PropertyEditorRegistrar editorRegistrar : editors.values()) {
        editorRegistrar.registerCustomEditors(registry);
    }
}

From source file:org.codehaus.groovy.grails.web.mapping.filter.UrlMappingsFilter.java

@Override
protected void initFilterBean() throws ServletException {
    super.initFilterBean();
    urlHelper.setUrlDecode(false);//from w  ww  .ja v a2  s  . co  m
    final ServletContext servletContext = getServletContext();
    final WebApplicationContext applicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    handlerInterceptors = WebUtils.lookupHandlerInterceptors(servletContext);
    application = WebUtils.lookupApplication(servletContext);
    viewResolver = WebUtils.lookupViewResolver(servletContext);
    ApplicationContext mainContext = application.getMainContext();
    urlConverter = mainContext.getBean(UrlConverter.BEAN_NAME, UrlConverter.class);
    if (application != null) {
        grailsConfig = new GrailsConfig(application);
    }

    Map<String, MimeTypeResolver> mimeTypeResolvers = applicationContext.getBeansOfType(MimeTypeResolver.class);
    if (!mimeTypeResolvers.isEmpty()) {
        mimeTypeResolver = mimeTypeResolvers.values().iterator().next();
    }
    this.allowHeaderForWrongHttpMethod = grailsConfig.get(WebUtils.SEND_ALLOW_HEADER_FOR_INVALID_HTTP_METHOD,
            Boolean.TRUE);
    createStackTraceFilterer();
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up all of the HandlerInterceptor instances registered for the application
 *
 * @param servletContext The ServletContext instance
 * @return An array of HandlerInterceptor instances
 *///from  w  w  w.jav a 2 s.c o  m
public static HandlerInterceptor[] lookupHandlerInterceptors(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    final Collection<HandlerInterceptor> allHandlerInterceptors = new ArrayList<HandlerInterceptor>();

    WebRequestInterceptor[] webRequestInterceptors = lookupWebRequestInterceptors(servletContext);
    for (WebRequestInterceptor webRequestInterceptor : webRequestInterceptors) {
        allHandlerInterceptors.add(new WebRequestHandlerInterceptorAdapter(webRequestInterceptor));
    }
    final Collection<HandlerInterceptor> handlerInterceptors = wac.getBeansOfType(HandlerInterceptor.class)
            .values();

    allHandlerInterceptors.addAll(handlerInterceptors);
    return allHandlerInterceptors.toArray(new HandlerInterceptor[allHandlerInterceptors.size()]);
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Looks up all of the WebRequestInterceptor instances registered with the application
 *
 * @param servletContext The ServletContext instance
 * @return An array of WebRequestInterceptor instances
 *//*  w  ww .ja  va 2s.c  om*/
public static WebRequestInterceptor[] lookupWebRequestInterceptors(ServletContext servletContext) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    final Collection<WebRequestInterceptor> webRequestInterceptors = wac
            .getBeansOfType(WebRequestInterceptor.class).values();
    return webRequestInterceptors.toArray(new WebRequestInterceptor[webRequestInterceptors.size()]);
}

From source file:org.geoserver.jdbcconfig.internal.JdbcConfigTestSupport.java

public void setUp() throws Exception {
    ConfigDatabase.LOGGER.setLevel(Level.FINER);
    // just to avoid hundreds of warnings in the logs about extension lookups with no app
    // context set
    WebApplicationContext applicationContext = Mockito.mock(WebApplicationContext.class);
    new GeoServerExtensions().setApplicationContext(applicationContext);
    when(applicationContext.getBeansOfType((Class) anyObject())).thenReturn(Collections.EMPTY_MAP);
    when(applicationContext.getBeanNamesForType((Class) anyObject())).thenReturn(new String[] {});
    ///*w ww.j  ava  2 s .c  o  m*/

    final File testDbDir = new File("target", "jdbcconfig");
    FileUtils.deleteDirectory(testDbDir);
    testDbDir.mkdirs();

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(connectionUrl);
    dataSource.setUsername("postgres");
    dataSource.setPassword("geo123");

    dataSource.setMinIdle(3);
    dataSource.setMaxActive(10);
    try {
        Connection connection = dataSource.getConnection();
        connection.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        dropDb(dataSource);
    } catch (Exception ignored) {
    }
    initDb(dataSource);

    XStreamInfoSerialBinding binding = new XStreamInfoSerialBinding(new XStreamPersisterFactory());

    catalog = new CatalogImpl();
    configDb = new ConfigDatabase(dataSource, binding);
    configDb.setCatalog(catalog);
    configDb.initDb(null);
}

From source file:org.geoserver.jdbcconfig.JDBCConfigTestSupport.java

protected void configureAppContext(WebApplicationContext appContext) {
    expect(appContext.getBeansOfType((Class) anyObject())).andReturn(Collections.EMPTY_MAP).anyTimes();
    expect(appContext.getBeanNamesForType((Class) anyObject())).andReturn(new String[] {}).anyTimes();

    ServletContext servletContext = createNiceMock(ServletContext.class);
    replay(servletContext);/*from   w  ww  .j  av  a 2s.c om*/

    expect(appContext.getServletContext()).andReturn(servletContext);
}

From source file:org.jahia.bin.TestServlet.java

protected void handleGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    //    should be protected in production
    //        if (System.getProperty("org.jahia.selftest") == null) {
    //            httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
    //            return;
    //        }/*from   ww  w  .  java 2s  .  c om*/

    final ProcessingContextFactory pcf = (ProcessingContextFactory) SpringContextSingleton.getInstance()
            .getContext().getBean(ProcessingContextFactory.class.getName());
    ProcessingContext ctx = null;

    try {
        // should send response wrapper !
        ctx = pcf.getContext(httpServletRequest, httpServletResponse, servletContext);
    } catch (JahiaException e) {
        logger.error("Error while trying to build ProcessingContext", e);
        return;
    }

    try {
        ctx.setOperationMode(ParamBean.EDIT);
        //            ctx.setEntryLoadRequest(new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, ctx.getLocales()));

        JahiaUser admin = JahiaAdminUser.getAdminUser(0);
        JCRSessionFactory.getInstance().setCurrentUser(admin);
        ctx.setTheUser(admin);
    } catch (JahiaException e) {
        logger.error("Error getting user", e);
    }

    try {
        String pathInfo = StringUtils.substringAfter(httpServletRequest.getPathInfo(), "/test");
        if (StringUtils.isNotEmpty(pathInfo)) {
            final Set<String> ignoreTests = getIgnoreTests();
            // Execute one test
            String className = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);
            try {
                JUnitCore junitcore = new JUnitCore();
                SurefireJUnitXMLResultFormatter xmlResultFormatter = new SurefireJUnitXMLResultFormatter(
                        httpServletResponse.getOutputStream());
                junitcore.addListener(xmlResultFormatter);
                Class testClass = Class.forName(className);
                List<Class> classes = getTestClasses(testClass, new ArrayList<Class>());
                if (classes.isEmpty()) {
                    Description description = Description.createSuiteDescription(testClass);
                    xmlResultFormatter.testRunStarted(description);
                    xmlResultFormatter.testRunFinished(new Result());
                } else {
                    junitcore.run(new FilterRequest(Request.classes(classes.toArray(new Class[classes.size()])),
                            new Filter() {

                                @Override
                                public boolean shouldRun(Description description) {
                                    return !ignoreTests.contains(description.getDisplayName());
                                }

                                @Override
                                public String describe() {
                                    return "Filter out Jahia configured methods";
                                }
                            }));
                }
            } catch (Exception e) {
                logger.error("Error executing test", e);
            }
        } else {
            WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext
                    .getAttribute(WebApplicationContext.class.getName() + ".jahiaModules");
            Map<String, TestBean> testBeans = webApplicationContext.getBeansOfType(TestBean.class);

            PrintWriter pw = httpServletResponse.getWriter();
            // Return the lists of available tests
            List<String> tests = new LinkedList<String>();
            SortedSet<TestBean> s = new TreeSet<TestBean>(testBeans.values());
            for (TestBean testBean : s) {
                for (String o : testBean.getTestCases()) {
                    tests.add(o);
                }
            }

            for (String c : tests) {
                pw.println(c);
            }
        }
    } finally {
        try {
            ctx.setUserGuest();
        } catch (JahiaException e) {
            logger.error(e.getMessage(), e);
        }
    }

}

From source file:org.jahia.bin.TestServlet.java

private Set<String> getIgnoreTests() {
    WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.class.getName() + ".jahiaModules");
    Map<String, TestBean> testBeans = webApplicationContext.getBeansOfType(TestBean.class);

    // Return the lists of available tests
    Set<String> ignoreTests = new HashSet<String>();

    SortedSet<TestBean> s = new TreeSet<TestBean>(testBeans.values());
    for (TestBean testBean : s) {
        if (testBean.getIgnoredTests() != null) {
            ignoreTests.addAll(testBean.getIgnoredTests());
        }/*from  w w  w.  j  a  v a2 s.c  o  m*/
    }

    return ignoreTests;
}

From source file:org.springframework.web.socket.server.endpoint.SpringConfigurator.java

@Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {

    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    if (wac == null) {
        String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?";
        logger.error(message);// w w w. ja va 2  s.c  o  m
        throw new IllegalStateException(message);
    }

    Map<String, T> beans = wac.getBeansOfType(endpointClass);
    if (beans.isEmpty()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Creating new @ServerEndpoint instance of type " + endpointClass);
        }
        return wac.getAutowireCapableBeanFactory().createBean(endpointClass);
    } else if (beans.size() == 1) {
        if (logger.isTraceEnabled()) {
            logger.trace("Using @ServerEndpoint singleton " + beans.keySet().iterator().next());
        }
        return beans.values().iterator().next();
    } else {
        // Should not happen ..
        String message = "Found more than one matching @ServerEndpoint beans of type " + endpointClass;
        logger.error(message);
        throw new IllegalStateException(message);
    }
}