Java Code Examples for org.springframework.web.context.support.WebApplicationContextUtils

The following examples show how to use org.springframework.web.context.support.WebApplicationContextUtils. 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: cosmo   Source File: CalendarCollectionProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param collectionItem
 * @return
 */
private Calendar getCalendarFromCollection(DavRequest req, CollectionItem collectionItem) {
    Calendar result = new Calendar();

    if (productId == null) {
        synchronized (this) {
            if (productId == null) {
                Environment environment = WebApplicationContextUtils
                        .findWebApplicationContext(req.getServletContext()).getEnvironment();
                productId = environment.getProperty(PRODUCT_ID_KEY);
            }
        }
    }

    result.getProperties().add(new ProdId(productId));
    result.getProperties().add(Version.VERSION_2_0);
    result.getProperties().add(CalScale.GREGORIAN);

    for (Item item : collectionItem.getChildren()) {
        if (!NoteItem.class.isInstance(item)) {
            continue;
        }
        for (Stamp s : item.getStamps()) {
            if (BaseEventStamp.class.isInstance(s)) {
                BaseEventStamp baseEventStamp = BaseEventStamp.class.cast(s);
                result.getComponents().add(baseEventStamp.getEvent());
            }
        }
    }
    return result;
}
 
Example 2
Source Project: geowave   Source File: GeoWaveApiKeySetterFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This class is only responsible for setting two servlet context attributes: "userName" and
 * "apiKey"
 */
@Override
public void doFilter(
    final ServletRequest request,
    final ServletResponse response,
    final FilterChain chain) throws IOException, ServletException {

  try {
    final ServletContext servletContext = getServletContext();
    final ApplicationContext ac =
        WebApplicationContextUtils.getWebApplicationContext(servletContext);
    final GeoWaveBaseApiKeyDB apiKeyDB = (GeoWaveBaseApiKeyDB) ac.getBean("apiKeyDB");
    final String userAndKey = apiKeyDB.getCurrentUserAndKey();

    if (!userAndKey.equals("")) {
      final String[] userAndKeyToks = userAndKey.split(":");
      servletContext.setAttribute("userName", userAndKeyToks[0]);
      servletContext.setAttribute("apiKey", userAndKeyToks[1]);
    }
  } catch (final Exception e) {
    return;
  } finally {
    chain.doFilter(request, response);
  }
}
 
Example 3
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
   	try {
		ServletContext servletContext = servletContextEvent.getServletContext();
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		ExecutorService workerExecutorService = (ExecutorService) webApplicationContext.getBean("WorkerExecutorService");
		Thread.sleep(1000);
		logger.info("Shutting down WorkerExecutorService");
		int retryCount = 0;
		while (!workerExecutorService.isTerminated() && retryCount < 10) {
			if (retryCount > 0) {
				logger.error("WorkerExecutorService shutdown retryCount: " + retryCount);
				Thread.sleep(1000);
			}
			workerExecutorService.shutdownNow();
			retryCount++;
		}
   	} catch (Exception e) {
		logger.error("Cannot shutdown WorkerExecutorService: " + e.getMessage(), e);
	}
}
 
Example 4
/**
 * Initializes CORS filter
 */
private void initCORS(ServletContext servletContext)
{
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    Properties gP = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES);
    Boolean corsEnabled = new Boolean(gP.getProperty(CORS_ENABLED));

    if(logger.isDebugEnabled())
    {
        logger.debug("CORS filter is" + (corsEnabled?" ":" not ") + "enabled");
    }
    if (corsEnabled)
    {
        FilterRegistration.Dynamic corsFilter = servletContext.addFilter("CorsFilter", "org.apache.catalina.filters.CorsFilter");
        corsFilter.setInitParameter(CORS_ALLOWED_ORIGINS, gP.getProperty(CORS_ALLOWED_ORIGINS));
        corsFilter.setInitParameter(CORS_ALLOWED_METHODS, gP.getProperty(CORS_ALLOWED_METHODS));
        corsFilter.setInitParameter(CORS_ALLOWED_HEADERS, gP.getProperty(CORS_ALLOWED_HEADERS));
        corsFilter.setInitParameter(CORS_EXPOSED_HEADERS, gP.getProperty(CORS_EXPOSED_HEADERS));
        corsFilter.setInitParameter(CORS_SUPPORT_CREDENTIALS, gP.getProperty(CORS_SUPPORT_CREDENTIALS));
        corsFilter.setInitParameter(CORS_PREFLIGHT_CREDENTIALS, gP.getProperty(CORS_PREFLIGHT_CREDENTIALS));
        corsFilter.addMappingForUrlPatterns(DISPATCHER_TYPE, false, "/*");
    }
}
 
Example 5
Source Project: lams   Source File: DelegatingFilterProxy.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the {@code WebApplicationContext} passed in at construction time, if available.
 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
 * the well-known "root" application context attribute. The
 * {@code WebApplicationContext} must have already been loaded and stored in the
 * {@code ServletContext} before this filter gets initialized (or invoked).
 * <p>Subclasses may override this method to provide a different
 * {@code WebApplicationContext} retrieval strategy.
 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
 * @see #DelegatingFilterProxy(String, WebApplicationContext)
 * @see #getContextAttribute()
 * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
 * @see WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
 */
protected WebApplicationContext findWebApplicationContext() {
	if (this.webApplicationContext != null) {
		// The user has injected a context at construction time -> use it...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
			ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.webApplicationContext;
			if (!cac.isActive()) {
				// The context has not yet been refreshed -> do so before returning it...
				cac.refresh();
			}
		}
		return this.webApplicationContext;
	}
	String attrName = getContextAttribute();
	if (attrName != null) {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
	}
	else {
		return WebApplicationContextUtils.findWebApplicationContext(getServletContext());
	}
}
 
Example 6
Source Project: jeecg   Source File: InitListener.java    License: Apache License 2.0 5 votes vote down vote up
public void contextInitialized(ServletContextEvent event) {
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		SystemService systemService = (SystemService) webApplicationContext.getBean("systemService");
//		MenuInitService menuInitService = (MenuInitService) webApplicationContext.getBean("menuInitService");
		MutiLangServiceI mutiLangService = (MutiLangServiceI) webApplicationContext.getBean("mutiLangService");
		DynamicDataSourceServiceI dynamicDataSourceService = (DynamicDataSourceServiceI) webApplicationContext.getBean("dynamicDataSourceService");
		
		/**
		 * 第一部分:对数据字典进行缓存
		 */
		systemService.initAllTypeGroups();
		systemService.initAllTSIcons();
		
		
//		/**
//		 * 第二部分:自动加载新增菜单和菜单操作权限
//		 * 说明:只会添加,不会删除(添加在代码层配置,但是在数据库层未配置的)
//		 */
//		if("true".equals(ResourceUtil.getConfigByName("auto.scan.menu.flag").toLowerCase())){
//			menuInitService.initMenu();
//		}
		
		/**
		 * 第三部分:加载多语言内容
		 */
		mutiLangService.initAllMutiLang();
		
		/**
		 * 第四部分:加载配置的数据源信息
		 */
		dynamicDataSourceService.initDynamicDataSource();
	}
 
Example 7
Source Project: layui-admin   Source File: ShiroConfigService.java    License: MIT License 5 votes vote down vote up
/**
 * 更新权限,解决需要重启tomcat才能生效权限的问题
 */
public void updatePermission() {
    try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ServletContext servletContext = request.getSession().getServletContext();
        AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("myShiroFilter");

        synchronized (shiroFilter) {
            // 获取过滤管理器
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
            // 清空初始权限配置
            manager.getFilterChains().clear();
            // 重新获取资源
            Map<String, String> chains = loadFilterChainDefinitions();

            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");

                manager.createChain(url, chainDefinition);
            }
            log.info("更新权限成功!!");
        }
    } catch (Exception e) {
        log.error("更新权限到shiro异常", e);
    }
}
 
Example 8
Source Project: lams   Source File: PortraitTag.java    License: GNU General Public License v2.0 5 votes vote down vote up
private IUserManagementService getUserManagementService() {
if (userManagementService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils
	    .getRequiredWebApplicationContext(pageContext.getServletContext());
    userManagementService = (IUserManagementService) ctx.getBean("userManagementService");
}
return userManagementService;
   }
 
Example 9
Source Project: qconfig   Source File: AbstractAccessLogFilter.java    License: MIT License 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
    if (context == null) {
        throw new ServletException("init failed");
    }

    this.clientInfoService = context.getBean(ClientInfoService.class);
    this.cacheConfigInfoService = (ConfigInfoService) context.getBean("cacheConfigInfoService");
    this.groupAccessService = context.getBean(DifferentGroupAccessService.class);
}
 
Example 10
/**
 * Look up the SessionFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the SessionFactory to use
 * @see #getSessionFactoryBeanName
 */
protected SessionFactory lookupSessionFactory() {
	if (logger.isDebugEnabled()) {
		logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
	}
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}
 
Example 11
@Override
public void init(ServletConfig config) throws ServletException {
	super.init(config);
	
   	this.applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
   	this.uidService = applicationContext.getBean( ExtensibleUIDConstants.SERVICE_BEAN_NAME, ExtensibleUIDService.class);
   	this.userFormExecuteService = applicationContext.getBean("UserFormExecutionService", UserFormExecutionService.class);
   	
      	final ComMailingDao mailingDao = applicationContext.getBean("MailingDao", ComMailingDao.class);
   	final ComBindingEntryDao bindingEntryDao = applicationContext.getBean("BindingEntryDao", ComBindingEntryDao.class);
   	
   	this.unsubscription = new Unsubscription(mailingDao, bindingEntryDao);
   	this.oneClickUnsubscription = new OneClickUnsubscription(this.unsubscription);
}
 
Example 12
Source Project: spring-analysis-note   Source File: ContextLoaderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testContextLoaderListenerWithProgrammaticInitializers() {
	MockServletContext sc = new MockServletContext("");
	sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
			"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
	ContextLoaderListener listener = new ContextLoaderListener();
	listener.setContextInitializers(new TestContextInitializer(), new TestWebContextInitializer());
	listener.contextInitialized(new ServletContextEvent(sc));
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	TestBean testBean = wac.getBean(TestBean.class);
	assertThat(testBean.getName(), equalTo("testName"));
	assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
 
Example 13
Source Project: SmartEducation   Source File: UserListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 容器初试话加载一些需要的service
 * @param sce
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
	// 获取容器与相关的Service对象
	ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
	userService = (IUserService) ac.getBean("userServiceImpl");
	userOnlineTimeService = (IUserOnlineTimeService) ac.getBean("userOnlineTimeServiceImpl");
}
 
Example 14
@Test
public void register() throws ServletException {
	initializer.onStartup(servletContext);

	assertTrue(eventListener instanceof ContextLoaderListener);
	ContextLoaderListener cll = (ContextLoaderListener) eventListener;
	cll.contextInitialized(new ServletContextEvent(servletContext));

	WebApplicationContext applicationContext = WebApplicationContextUtils
			.getRequiredWebApplicationContext(servletContext);

	assertTrue(applicationContext.containsBean(BEAN_NAME));
	assertTrue(applicationContext.getBean(BEAN_NAME) instanceof MyBean);
}
 
Example 15
Source Project: ZTuoExchange_framework   Source File: LogInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    int index = request.getContextPath().length();
    String uri = request.getRequestURI().substring(index);
    String method = request.getMethod();
    String ip = remoteIp(request);
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    AccessLog al = handlerMethod.getMethodAnnotation(AccessLog.class);
    if (al != null) {
        AdminModule module = al.module();
        String operation = al.operation();
        log.info("module={},operation={}", module, operation);
        int dotIndex = uri.lastIndexOf(".");
        String accessRuleUri = dotIndex > 0 ? uri.substring(0, dotIndex) : uri;
        Admin admin = (Admin) request.getSession().getAttribute(SysConstant.SESSION_ADMIN);
        long adminUid = admin == null ? -1 : admin.getId();
        AdminAccessLog adminAccessLog = new AdminAccessLog();
        adminAccessLog.setAdminId(adminUid);
        adminAccessLog.setAccessIp(ip);
        adminAccessLog.setAccessMethod(method);
        adminAccessLog.setOperation(operation);
        adminAccessLog.setModule(module);
        adminAccessLog.setUri(accessRuleUri);
        //解决service为null无法注入问题
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        AdminAccessLogService logService = (AdminAccessLogService) factory.getBean("adminAccessLogService");
        logService.saveLog(adminAccessLog);
    }

    return true;
}
 
Example 16
Source Project: sds   Source File: ServerListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    springContext = WebApplicationContextUtils
            .getWebApplicationContext(event.getServletContext());
    initService = springContext.getBean(InitService.class);
    initService.start();

}
 
Example 17
Source Project: lams   Source File: CommandWebsocketServer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static ILearnerFullService getLearnerService() {
if (learnerService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils
	    .getWebApplicationContext(SessionManager.getServletContext());
    learnerService = (ILearnerFullService) ctx.getBean("learnerService");
}
return learnerService;
   }
 
Example 18
Source Project: archiva   Source File: TemporaryGroupIndexSessionCleaner.java    License: Apache License 2.0 5 votes vote down vote up
private IndexMerger getIndexMerger( HttpSessionEvent httpSessionEvent )
{
    if ( indexMerger == null )
    {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(
            httpSessionEvent.getSession().getServletContext() );
        indexMerger = webApplicationContext.getBean( IndexMerger.class );
    }
    return indexMerger;
}
 
Example 19
@Test  // SPR-12553
public void applicationContextAttribute() {
	TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController());
	builder.addPlaceholderValue("sys.login.ajax", "/foo");
	WebApplicationContext  wac = builder.initWebAppContext();
	assertEquals(wac, WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext()));
}
 
Example 20
Source Project: mPaaS   Source File: TraceFilter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化
 *
 * @throws ServletException
 */
@Override
protected void initFilterBean() throws ServletException {
    super.initFilterBean();
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    traceConfig=applicationContext.getBean(TraceConfig.class);
}
 
Example 21
@Test
public void register() throws ServletException {
	initializer.onStartup(servletContext);

	assertTrue(eventListener instanceof ContextLoaderListener);
	ContextLoaderListener cll = (ContextLoaderListener) eventListener;
	cll.contextInitialized(new ServletContextEvent(servletContext));

	WebApplicationContext applicationContext = WebApplicationContextUtils
			.getRequiredWebApplicationContext(servletContext);

	assertTrue(applicationContext.containsBean(BEAN_NAME));
	assertTrue(applicationContext.getBean(BEAN_NAME) instanceof MyBean);
}
 
Example 22
Source Project: flowable-engine   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    LOGGER.info("Destroying Web application");
    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
    AnnotationConfigWebApplicationContext gwac = (AnnotationConfigWebApplicationContext) ac;
    gwac.close();
    LOGGER.debug("Web application destroyed");
}
 
Example 23
Source Project: olat   Source File: CoreSpringFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param beanName
 *            The bean name to check for. Be sure the bean does exist, otherwise an NoSuchBeanDefinitionException will be thrown
 * @return The bean
 */
public static Object getBean(String beanName) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    Object o = context.getBean(beanName);
    beanNamesCalledFromSource.add(beanName);
    // printClassNamesOfAllBeans(context);
    return o;
}
 
Example 24
Source Project: qconfig   Source File: AccessLogV1Filter.java    License: MIT License 5 votes vote down vote up
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
    if (context == null) {
        throw new ServletException("init failed");
    }

    this.qFileFactory = (QFileFactory) context.getBean("v1Factory");
}
 
Example 25
Source Project: cia   Source File: AbstractClickListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the application manager.
 *
 * @return the application manager
 */
protected ApplicationManager getApplicationManager() {
	return WebApplicationContextUtils
			.getWebApplicationContext(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
					.getRequest().getSession(true).getServletContext())
			.getBean(ApplicationManager.class);
}
 
Example 26
Source Project: ZTuoExchange_framework   Source File: SessionInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example 27
Source Project: ZTuoExchange_framework   Source File: SessionInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example 28
Source Project: lams   Source File: SsoHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
private IUserManagementService getUserManagementService(ServletContext context) {
if (SsoHandler.userManagementService == null) {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
    SsoHandler.userManagementService = (UserManagementService) ctx.getBean("userManagementService");
}
return SsoHandler.userManagementService;
   }
 
Example 29
@Override
public void init() throws ServletException {
    super.init();

    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    this.userActivityLogService = ctx.getBean(UserActivityLogService.class);
}
 
Example 30
Source Project: syncope   Source File: ApacheDSStartStopListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the server. It creates the partition, adds the index, and injects the context entries for the created
 * partitions.
 *
 * @param workDir the directory to be used for storing the data
 * @param loadDefaultContent if default content should be loaded
 * @throws Exception if there were some problems while initializing
 */
private void initDirectoryService(final ServletContext servletContext, final File workDir,
        final boolean loadDefaultContent) throws Exception {

    // Initialize the LDAP service
    service = new DefaultDirectoryService();
    service.setInstanceLayout(new InstanceLayout(workDir));

    // first load the schema
    initSchemaPartition();

    // then the system partition
    initSystemPartition();

    // Disable the ChangeLog system
    service.getChangeLog().setEnabled(false);
    service.setDenormalizeOpAttrsEnabled(true);

    // Now we can create as many partitions as we need
    addPartition("isp", "o=isp", service.getDnFactory());

    // And start the service
    service.startup();

    if (loadDefaultContent) {
        Resource contentLdif = Objects.requireNonNull(
            WebApplicationContextUtils.getWebApplicationContext(servletContext))
            .getResource("classpath:/content.ldif");
        LdifInputStreamLoader contentLoader = new LdifInputStreamLoader(service.getAdminSession(),
            contentLdif.getInputStream());
        int numEntries = contentLoader.execute();
        LOG.info("Successfully created {} entries", numEntries);
    }
}