Rebuild the search index during context initialization.

@param servletContextEvent The context event (not really used).
163162
@Override
    public void contextInitialized(
            final ServletContextEvent servletContextEvent) {
        logger.info("Rebuilding Search Index...");

        // Build the session factory.
        SessionFactory factory = createSessionFactory();

        // Build the hibernate session.
        Session session = factory.openSession();

        // Create the fulltext session.
        FullTextSession fullTextSession = Search.getFullTextSession(session);

        try {
            fullTextSession
                    .createIndexer()
                    .startAndWait();
        } catch (InterruptedException e) {
            logger.warn("Search reindex interrupted. Good luck!");
            logger.trace("Error:", e);
        } finally {
            // Close everything and release the lock file.
            session.close();
            factory.close();
        }
    }
239853
public void contextInitialized(ServletContextEvent event) {
        this.context = event.getServletContext();

        // Output a simple message to the server's console
        System.out.println("The Simple Web App. Is Ready");

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "/client.xml");
        LocatorService client = (LocatorService) context
                .getBean("locatorService");

        String serviceHost = this.context.getInitParameter("serviceHost");

        try {
            client.registerEndpoint(new QName(
                    "http://talend.org/esb/examples/", "GreeterService"),
                    serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);
        } catch (InterruptedExceptionFault e) {
            e.printStackTrace();
        } catch (ServiceLocatorFault e) {
            e.printStackTrace();
        }
    }
928268
public void associate(ServletContext context) {
		context.setAttribute(COMPONENTS, new ConcurrentHashMap<Descriptor<?>, Object>());
		this.context = context;
	}
1020310
static final Context context(Element match, int matchIndex, int matchSize) {
        return new DefaultContext(match, matchIndex, matchSize);
    }
147377
private static void initURLTemplates( ServletContext servletContext )
    {
        TemplatedURLFormatter formatter = TemplatedURLFormatter.getTemplatedURLFormatter( servletContext );
        if ( formatter == null )
        {
            // get the default template formatter class name from the config file
            formatter = getTemplatedURLFormatter();

            assert formatter != null : "Found a non-null URL formatter";

            // set the TemplatedURLFormatter attribute on the context.
            TemplatedURLFormatter.initServletContext( servletContext, formatter );
        }

        URLTemplatesFactory templatesFactory = URLTemplatesFactory.getURLTemplatesFactory( servletContext );
        if ( templatesFactory == null )
        {
            // URLTemplatesFactory has not been initialized,
            // get a URLTemplatesFactory object from the containerAdapter.
            templatesFactory = PageFlowUtils.createURLTemplatesFactory( servletContext );

            // get the known/req tokens from the default formatter for the factory to use to verify templates
            templatesFactory.setKnownTokens( formatter.getKnownTokens() );
            templatesFactory.setRequiredTokens( formatter.getRequiredTokens() );
            templatesFactory.load( servletContext );

            // set the URLTemplatesFactory attribute on the context.
            URLTemplatesFactory.initServletContext( servletContext, templatesFactory );
        }
    }
354519
@NonNull public Context getContext() {
        if (searchView != null) {
            return searchView.getContext();
        } else if (supportView != null) {
            return supportView.getContext();
        }
        throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
    }
86626
public void initialize(ContextRefreshedEvent event) {
    ApplicationContext ctx = event.getApplicationContext();
    Stream<String> languageCodes = LanguageService.getLanguageCodes();

    EntityTypeMetadata entityTypeMeta = ctx.getBean(EntityTypeMetadata.class);
    AttributeMetadata attrMetaMeta = ctx.getBean(AttributeMetadata.class);
    L10nStringMetadata l10nStringMeta = ctx.getBean(L10nStringMetadata.class);

    languageCodes.forEach(
        languageCode -> {
          entityTypeMeta
              .addAttribute(getI18nAttributeName(EntityTypeMetadata.LABEL, languageCode))
              .setNillable(true)
              .setLabel("Label (" + languageCode + ')');
          entityTypeMeta
              .addAttribute(getI18nAttributeName(EntityTypeMetadata.DESCRIPTION, languageCode))
              .setNillable(true)
              .setLabel("Description (" + languageCode + ')')
              .setDataType(TEXT);
          attrMetaMeta
              .addAttribute(getI18nAttributeName(AttributeMetadata.LABEL, languageCode))
              .setNillable(true)
              .setLabel("Label (" + languageCode + ')');
          attrMetaMeta
              .addAttribute(getI18nAttributeName(AttributeMetadata.DESCRIPTION, languageCode))
              .setNillable(true)
              .setLabel("Description (" + languageCode + ')')
              .setDataType(TEXT);
          l10nStringMeta.addAttribute(languageCode).setNillable(true).setDataType(TEXT);
        });
  }
551196
@EventListener
    public void init(ContextRefreshedEvent event) {
        idTokenFactory = context.getBean(IdTokenFactory.class);

        // Make sure we have a guestUsernameSelectors collection & sort it
        if (guestUsernameSelectors == null) {
            guestUsernameSelectors = Collections.emptyList();
        }
        Collections.sort(guestUsernameSelectors);
    }
747433
public static void init(Context contextValue, ExecutorService service) {
		context = contextValue;

		if (service == null) {
			executerService = Executors.newFixedThreadPool(THREAD_POOL_SIZE_DEFAULT);
		} else {
			executerService = service;
		}

	}
175690
@Override
    public void contextInitialized(ServletContextEvent evt) {
        File usersDir = new File(SetupOptions.getBaseConfigDirectory(), "users");
        if (!usersDir.isDirectory()) {
            return;
        }
        DocumentBuilder domBuilder = null;
        try {
            domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGR.warning(e.getMessage());
            return;
        }
        DOMImplementationLS lsFactory = buildDOM3LoadAndSaveFactory();
        LSSerializer serializer = lsFactory.createLSSerializer();
        serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
        serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
        LSOutput output = lsFactory.createLSOutput();
        output.setEncoding("UTF-8");
        for (File userDir : usersDir.listFiles()) {
            File userFile = new File(userDir, "user.xml");
            if (!userFile.isFile()) {
                continue;
            }
            try {
                Document doc = domBuilder.parse(userFile);
                Node pwNode = doc.getElementsByTagName("password").item(0);
                if (null == pwNode) {
                    continue;
                }
                String password = pwNode.getTextContent();
                if (password.split(":").length == 5) {
                    break;
                }
                pwNode.setTextContent(PasswordStorage.createHash(password));
                // overwrite contents of file
                // Fortify Mod: Make sure that the output stream is closed
                // output.setByteStream(new FileOutputStream(userFile, false));
                FileOutputStream os = new FileOutputStream(userFile, false);
                output.setByteStream(os);
                serializer.write(doc, output);
                os.close();
            } catch (Exception e) {
                LOGR.info(e.getMessage());
                continue;
            }
        }
    }
54072
@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        if (isSpringBoot){
            CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
            if (!crawlerProperties.isEnabled()){
                logger.warn("{} is not enabled",Constants.SEIMI_CRAWLER_BOOTSTRAP_ENABLED);
                return;
            }
        }

        if (context != null) {
            if (CollectionUtils.isEmpty(CrawlerCache.getCrawlers())) {
                logger.info("Not find any crawler,may be you need to check.");
                return;
            }
            workersPool = Executors.newFixedThreadPool(Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors() * CrawlerCache.getCrawlers().size());
            for (Class<? extends BaseSeimiCrawler> a : CrawlerCache.getCrawlers()) {
                CrawlerModel crawlerModel = new CrawlerModel(a, context);
                if (CrawlerCache.isExist(crawlerModel.getCrawlerName())) {
                    logger.error("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName());
                    throw new SeimiInitExcepiton(StrFormatUtil.info("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName()));
                }
                CrawlerCache.putCrawlerModel(crawlerModel.getCrawlerName(), crawlerModel);
            }

            for (Map.Entry<String, CrawlerModel> crawlerEntry : CrawlerCache.getCrawlerModelContext().entrySet()) {
                for (int i = 0; i < Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors(); i++) {
                    workersPool.execute(new SeimiProcessor(CrawlerCache.getInterceptors(), crawlerEntry.getValue()));
                }
            }

            if (isSpringBoot){
                CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
                String crawlerNames = crawlerProperties.getNames();
                if (StringUtils.isBlank(crawlerNames)){
                    logger.info("Spring boot start [{}] as worker.",StringUtils.join(CrawlerCache.getCrawlerModelContext().keySet(),","));
                }else {
                    String[] crawlers = crawlerNames.split(",");
                    for (String cn:crawlers){
                        CrawlerModel crawlerModel = CrawlerCache.getCrawlerModel(cn);
                        if (crawlerModel == null){
                            logger.warn("Crawler name = {} is not existent.",cn);
                            continue;
                        }
                        crawlerModel.startRequest();
                    }
                }
                //统一通用配置信息至 seimiConfig
                SeimiConfig config = new SeimiConfig();
                config.setBloomFilterExpectedInsertions(crawlerProperties.getBloomFilterExpectedInsertions());
                config.setBloomFilterFalseProbability(crawlerProperties.getBloomFilterFalseProbability());
                config.setSeimiAgentHost(crawlerProperties.getSeimiAgentHost());
                config.setSeimiAgentPort(crawlerProperties.getSeimiAgentPort());
                CrawlerCache.setConfig(config);
            }
        }
    }
949937
public void init()
    {
        ServletContext config=getServletContext();
        _servletHandler=((ServletHandler.Context)config).getServletHandler();

        Enumeration e = getInitParameterNames();
        while(e.hasMoreElements())
        {
            String param=(String)e.nextElement();
            String value=getInitParameter(param);
            String lvalue=value.toLowerCase();
            if ("nonContextServlets".equals(param))
            {
                _nonContextServlets=value.length()>0 && lvalue.startsWith("t");
            }
            if ("verbose".equals(param))
            {
                _verbose=value.length()>0 && lvalue.startsWith("t");
            }
            else
            {
                if (_parameters==null)
                    _parameters=new HashMap();
                _parameters.put(param,value);
            }
        }
    }
57714
public static void initServletContext( ServletContext servletContext, URLTemplatesFactory templatesFactory )
    {
        assert servletContext != null : "The ServletContext cannot be null.";

        if ( servletContext == null )
        {
            throw new IllegalArgumentException( "The ServletContext cannot be null." );
        }

        servletContext.setAttribute( URL_TEMPLATE_FACTORY_ATTR, templatesFactory );
    }
976553
protected void initializeContext(
            @Nonnull List<BeanDefinitionReference> contextScopeBeans,
            @Nonnull List<BeanDefinitionReference> processedBeans) {

        if (CollectionUtils.isNotEmpty(contextScopeBeans)) {
            final Collection<BeanDefinition> contextBeans = new ArrayList<>();

            for (BeanDefinitionReference contextScopeBean : contextScopeBeans) {
                try {
                    loadContextScopeBean(contextScopeBean, contextBeans::add);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeBean.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            filterProxiedTypes((Collection) contextBeans, true, false);
            filterReplacedBeans((Collection) contextBeans);

            for (BeanDefinition contextScopeDefinition: contextBeans) {
                try {
                    loadContextScopeBean(contextScopeDefinition);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeDefinition.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            contextBeans.clear();
        }

        if (!processedBeans.isEmpty()) {

            @SuppressWarnings("unchecked") Stream<BeanDefinitionMethodReference<?, ?>> methodStream = processedBeans
                    .stream()
                    // is the bean reference enabled
                    .filter(ref -> ref.isEnabled(this))
                    // ok - continue and load it
                    .map((Function<BeanDefinitionReference, BeanDefinition<?>>) reference -> {
                        try {
                            return reference.load(this);
                        } catch (Exception e) {
                            throw new BeanInstantiationException("Bean definition [" + reference.getName() + "] could not be loaded: " + e.getMessage(), e);
                        }
                    })
                    // is the bean itself enabled
                    .filter(bean -> bean.isEnabled(this))
                    // ok continue and get all of the ExecutableMethod references
                    .flatMap(beanDefinition ->
                            beanDefinition.getExecutableMethods()
                                    .parallelStream()
                                    .map((Function<ExecutableMethod<?, ?>, BeanDefinitionMethodReference<?, ?>>) executableMethod ->
                                            BeanDefinitionMethodReference.of((BeanDefinition) beanDefinition, executableMethod)
                                    )
                    );

            // group the method references by annotation type such that we have a map of Annotation -> MethodReference
            // ie. Class<Scheduled> -> @Scheduled void someAnnotation()
            Map<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> byAnnotation = methodStream
                    .collect(
                            Collectors.groupingBy((Function<ExecutableMethod<?, ?>, Class<? extends Annotation>>) executableMethod ->
                                    executableMethod.getAnnotationTypeByStereotype(Executable.class)
                                            .orElseThrow(() ->
                                                    new IllegalStateException("BeanDefinition.requiresMethodProcessing() returned true but method has no @Executable definition. This should never happen. Please report an issue.")
                                            )));

            // Find ExecutableMethodProcessor for each annotation and process the BeanDefinitionMethodReference
            for (Map.Entry<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> entry : byAnnotation.entrySet()) {
                Class<? extends Annotation> annotationType = entry.getKey();
                streamOfType(ExecutableMethodProcessor.class, Qualifiers.byTypeArguments(annotationType))
                        .forEach(processor -> {
                            for (BeanDefinitionMethodReference<?, ?> method : entry.getValue()) {

                                BeanDefinition<?> beanDefinition = method.getBeanDefinition();

                                // Only process the method if the the annotation is not declared at the class level
                                // If declared at the class level it will already have been processed by AnnotationProcessorListener
                                if (!beanDefinition.hasStereotype(annotationType)) {
                                    //noinspection unchecked
                                    if (method.hasDeclaredStereotype(Parallel.class)) {
                                        ForkJoinPool.commonPool().execute(() -> {
                                            try {
                                                processor.process(beanDefinition, method);
                                            } catch (Throwable e) {
                                                if (LOG.isErrorEnabled()) {
                                                    LOG.error("Error processing bean method " + beanDefinition + "." + method + " with processor (" + processor + "): " + e.getMessage(), e);
                                                }
                                                Boolean shutdownOnError = method.getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true);
                                                if (shutdownOnError) {
                                                    stop();
                                                }
                                            }
                                        });
                                    } else {
                                        processor.process(beanDefinition, method);
                                    }
                                }
                            }

                            if (processor instanceof Completable) {
                                ((Completable) processor).onComplete();
                            }

                        });
            }
        }

        final Runnable runnable = () ->
                beanDefinitionsClasses.removeIf((BeanDefinitionReference beanDefinitionReference) ->
                        !beanDefinitionReference.isEnabled(this));
        if (ClassLoadingReporter.isReportingEnabled()) {
            // do this in a blocking manner so that reporting is immediately aware of missing classes
            runnable.run();
        } else {
            // proactively remove bean definitions that are not enabled
            new Thread(runnable).start();
        }

    }
891812
@Override
    public void setContext(DisplayContext context) {
        super.setContext(context);
        if (!capitalizationInfoIsSet &&
              (context==DisplayContext.CAPITALIZATION_FOR_UI_LIST_OR_MENU || context==DisplayContext.CAPITALIZATION_FOR_STANDALONE)) {
            initCapitalizationContextInfo(fLocale);
            capitalizationInfoIsSet = true;
        }
        if (capitalizationBrkIter == null && (context==DisplayContext.CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
              (context==DisplayContext.CAPITALIZATION_FOR_UI_LIST_OR_MENU && capitalizationOfRelativeUnitsForListOrMenu) ||
              (context==DisplayContext.CAPITALIZATION_FOR_STANDALONE && capitalizationOfRelativeUnitsForStandAlone) )) {
            capitalizationBrkIter = BreakIterator.getSentenceInstance(fLocale);
        }
    }
775482
@Override
    public void contextInitialized(ServletContextEvent contextEvent) {
        configSupport = new ServletContexConfigSupport();
        if (configSupport.hasHandlers(contextEvent.getServletContext())) {
            AuditManager.startWithConfiguration(configSupport.loadConfig(contextEvent.getServletContext()));
        } else {
            AuditManager.getInstance();
        }
    }
626143
protected void refresh(ApplicationContext applicationContext) {
		Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
		((AbstractApplicationContext) applicationContext).refresh();
	}