Example usage for org.springframework.context ApplicationEvent getSource

List of usage examples for org.springframework.context ApplicationEvent getSource

Introduction

In this page you can find the example usage for org.springframework.context ApplicationEvent getSource.

Prototype

public Object getSource() 

Source Link

Document

The object on which the Event initially occurred.

Usage

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Called to handle a Spring application context event.
 */// w  w  w  .j a  v  a2 s.c om
public void onApplicationEvent(ApplicationEvent applicationEvent) {
    Log logger = this.getLog();

    synchronized (super.getLock()) {
        if (applicationEvent.getSource() == this.parentApplicationContext) {
            if (logger.isDebugEnabled())
                logger.debug("Parent Spring ApplicationContext initialized.");
            applicationContextInitialized = true;
        }
    }
}

From source file:net.sf.housekeeper.swing.category.CategoriesView.java

public void onApplicationEvent(ApplicationEvent e) {
    if (e instanceof HousekeeperEvent) {
        final HousekeeperEvent le = (HousekeeperEvent) e;

        if (le.objectIs(Category.class)) {
            if (le.isEventType(HousekeeperEvent.ADDED)) {
                tree.addCategory((Category) e.getSource());
                tree.setSelectedCategory((Category) e.getSource());
            } else if (le.isEventType(HousekeeperEvent.REMOVED)) {
                tree.removeCategory((Category) e.getSource());
            } else if (le.isEventType(HousekeeperEvent.MODIFIED)) {
                tree.removeCategory((Category) e.getSource());
                tree.addCategory((Category) e.getSource());
                tree.setSelectedCategory((Category) e.getSource());
            }// w  w  w  .  j  av  a  2  s .  c  o m
        } else if (le.isEventType(HousekeeperEvent.DATA_REPLACED)) {
            refresh();
        }
    }

}

From source file:org.acegisecurity.concurrent.SessionRegistryImpl.java

public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof HttpSessionDestroyedEvent) {
        String sessionId = ((HttpSession) event.getSource()).getId();
        removeSessionInformation(sessionId);
    }//from  www  .j a  v a2s .co m
}

From source file:org.alfresco.repo.content.filestore.FileContentStore.java

public void onApplicationEvent(ApplicationEvent event) {
    // Once the context has been refreshed, we tell other interested beans about the existence of this content store
    // (e.g. for monitoring purposes)
    if (event instanceof ContextRefreshedEvent && event.getSource() == this.applicationContext) {
        publishEvent(((ContextRefreshedEvent) event).getApplicationContext(),
                Collections.<String, Serializable>emptyMap());
    }//w  w  w  .  j  a va  2 s  .c o m
}

From source file:org.alfresco.repo.descriptor.DescriptorServiceImpl.java

/**
 * On bootstrap load the special services for LicenseComponent and HeartBeat
 * /*w w  w . j  a  va2  s  . c  om*/
 * Also set installedRepoDescriptor and update current
 */
@Override
protected void onBootstrap(ApplicationEvent event) {
    AuthenticationUtil.RunAsWork<Void> bootstrapWork = new RunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            bootstrap();
            return null;
        }
    };
    AuthenticationUtil.runAs(bootstrapWork, AuthenticationUtil.getSystemUserName());
    isBootstrapped = true;
    // Broadcast that the descriptor service is now available
    ((ApplicationContext) event.getSource()).publishEvent(new DescriptorServiceAvailableEvent(this));
}

From source file:org.alfresco.repo.dictionary.DictionaryRepositoryBootstrap.java

@Override
protected void onBootstrap(ApplicationEvent event) {
    // Reset the dictionary (destroy and reload) in order to ensure that we have a basic version of
    // the dictionary (static models) loaded at least
    dictionaryDAO.reset();//from   ww  w  . j  a va  2 s . co m

    // Register listeners, which will be called when the dictionary is next reloaded
    register();

    // Trigger a reload.  The callbacks will occur immediately on the current thread, however,
    // the model created in reset() will still be available for the basic necessities
    dictionaryDAO.init();

    // The listeners can now know about this
    // However, the listeners will be needing to access the dictionary themselves, hence the earlier 'reset'
    // to ensure that there is no deadlock waiting for a new dictionary
    ((ApplicationContext) event.getSource()).publishEvent(new DictionaryRepositoryBootstrappedEvent(this));
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

@Override
public synchronized void onBootstrap(ApplicationEvent event) {
    if (event != null) {
        // Use the application context to load resources
        rpr = (ApplicationContext) event.getSource();
    }/*from w  w  w .  ja v  a2  s. c o  m*/

    // do everything in a transaction
    Session session = getSessionFactory().openSession();
    Connection connection = null;
    try {
        // make sure that we AUTO-COMMIT
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        LogUtil.info(logger, MSG_DATABASE_USED, connection);

        Configuration cfg = localSessionFactory.getConfiguration();

        // Check and dump the dialect being used
        checkDialect(this.dialect);

        // Ensure that our static connection provider is used
        String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER);
        cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName());
        SchemaBootstrapConnectionProvider.setBootstrapConnection(connection);

        // Update the schema, if required.
        if (updateSchema) {
            // Retries are required here as the DB lock will be applied lazily upon first statement execution.
            // So if the schema is up to date (no statements executed) then the LockFailException cannot be
            // thrown.  If it is thrown, the the update needs to be rerun as it will probably generate no SQL
            // statements the second time around.
            boolean updatedSchema = false;
            boolean createdSchema = false;

            for (int i = 0; i < schemaUpdateLockRetryCount; i++) {
                try {
                    createdSchema = updateSchema(cfg, session, connection);
                    updatedSchema = true;
                    break;
                } catch (LockFailedException e) {
                    try {
                        this.wait(schemaUpdateLockRetryWaitSeconds * 1000L);
                    } catch (InterruptedException ee) {
                    }
                }
            }

            if (!updatedSchema) {
                // The retries were exceeded
                throw new AlfrescoRuntimeException(ERR_PREVIOUS_FAILED_BOOTSTRAP);
            }

            // Copy the executed statements to the output file
            File schemaOutputFile = null;
            if (schemaOuputFilename != null) {
                schemaOutputFile = new File(schemaOuputFilename);
            } else {
                schemaOutputFile = TempFileProvider.createTempFile(
                        "AlfrescoSchema-" + this.dialect.getClass().getSimpleName() + "-All_Statements-",
                        ".sql");
            }

            StringBuilder executedStatements = executedStatementsThreadLocal.get();
            if (executedStatements == null) {
                LogUtil.info(logger, MSG_NO_CHANGES);
            } else {
                FileContentWriter writer = new FileContentWriter(schemaOutputFile);
                writer.setEncoding("UTF-8");
                String executedStatementsStr = executedStatements.toString();
                writer.putContent(executedStatementsStr);
                LogUtil.info(logger, MSG_ALL_STATEMENTS, schemaOutputFile.getPath());
            }

            if (!createdSchema) {
                // verify that all patches have been applied correctly 
                checkSchemaPatchScripts(cfg, connection, preUpdateScriptPatches, false); // check scripts
                checkSchemaPatchScripts(cfg, connection, postUpdateScriptPatches, false); // check scripts
            }

            if (executedStatements != null) {
                // Remove the flag indicating a running bootstrap
                setBootstrapCompleted(connection);
            }

            // Report normalized dumps
            if (executedStatements != null) {
                // Validate the schema, post-upgrade
                validateSchema("Alfresco-{0}-Validation-Post-Upgrade-{1}-", null);

                // 4.0+ schema dump
                dumpSchema("post-upgrade");
            }
        } else {
            LogUtil.info(logger, MSG_BYPASSING_SCHEMA_UPDATE);
        }

        if (stopAfterSchemaBootstrap) {
            // 4.0+ schema dump
            dumpSchema("forced-exit");
            LogUtil.error(logger, ERR_FORCED_STOP);
            throw new BootstrapStopException();
        }

        // Reset the configuration
        cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass);

        if (event != null) {
            // all done successfully
            ((ApplicationContext) event.getSource()).publishEvent(new SchemaAvailableEvent(this));
        }
    } catch (BootstrapStopException e) {
        // We just let this out
        throw e;
    } catch (Throwable e) {
        LogUtil.error(logger, e, ERR_UPDATE_FAILED);
        if (updateSchema) {
            throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e);
        } else {
            throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e);
        }
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Throwable e) {
            logger.warn("Error closing DB connection: " + e.getMessage());
        }
        try {
            if (session != null) {
                session.close();
            }
        } catch (Throwable e) {
            logger.warn("Error closing Hibernate session: " + e.getMessage());
        }
        // Remove the connection reference from the threadlocal boostrap
        SchemaBootstrapConnectionProvider.setBootstrapConnection(null);

    }
}

From source file:org.alfresco.repo.management.SafeApplicationEventMulticaster.java

@Override
public void multicastEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent && event.getSource() == this.appContext) {
        this.isApplicationStarted = true;
        for (ApplicationEvent queuedEvent : this.queuedEvents) {
            multicastEventInternal(queuedEvent);
        }//w w  w.j  a  v a  2s . c  o  m
        this.queuedEvents.clear();
        multicastEventInternal(event);
    } else if (event instanceof ContextClosedEvent && event.getSource() == this.appContext) {
        this.isApplicationStarted = false;
        multicastEventInternal(event);
    } else if (this.isApplicationStarted) {
        multicastEventInternal(event);
    } else {
        this.queuedEvents.add(event);
    }
}

From source file:org.alfresco.repo.management.SafeApplicationEventMulticaster.java

/**
 * Return a Collection of ApplicationListeners matching the given event
 * type. Non-matching listeners get excluded early.
 * //from   w ww.ja va  2 s  . c o  m
 * @param event
 *            the event to be propagated. Allows for excluding non-matching
 *            listeners early, based on cached matching information.
 * @return a Collection of ApplicationListeners
 * @see org.springframework.context.ApplicationListener
 */
protected Collection<ApplicationListener> getApplicationListeners(ApplicationEvent event) {
    Class<? extends ApplicationEvent> eventType = event.getClass();
    Class sourceType = event.getSource().getClass();
    ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);
    ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
    if (retriever != null) {
        return retriever.getApplicationListeners();
    } else {
        retriever = new ListenerRetriever(true);
        LinkedList<ApplicationListener> allListeners = new LinkedList<ApplicationListener>();
        synchronized (this.defaultRetriever) {
            if (!this.defaultRetriever.applicationListenerBeans.isEmpty()) {
                BeanFactory beanFactory = getBeanFactory();
                for (String listenerBeanName : this.defaultRetriever.applicationListenerBeans) {
                    ApplicationListener listener = beanFactory.getBean(listenerBeanName,
                            ApplicationListener.class);
                    if (supportsEvent(listener, eventType, sourceType)) {
                        retriever.applicationListenerBeans.add(listenerBeanName);
                        allListeners.add(listener);
                    }
                }
            }
            for (ApplicationListener listener : this.defaultRetriever.applicationListeners) {
                if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
                    retriever.applicationListeners.add(listener);
                    allListeners.add(listener);
                }
            }
            OrderComparator.sort(allListeners);
            this.retrieverCache.put(cacheKey, retriever);
        }
        if (log.isDebugEnabled()) {
            log.debug(allListeners.toString());
        }
        return allListeners;
    }
}

From source file:org.alfresco.repo.management.subsystems.AbstractPropertyBackedBean.java

/**
 * {@inheritDoc}//from   w w w.  j a  v  a  2s .c o  m
 */
public void onApplicationEvent(ApplicationEvent event) {
    if (this.autoStart && event instanceof ContextRefreshedEvent && event.getSource() == this.parent) {
        this.lock.writeLock().lock();
        try {
            start(false, false);
        } catch (Exception e) {
            // Let's log and swallow auto-start exceptions so that they are non-fatal. This means that the system
            // can hopefully be brought up to a level where its configuration can be edited and corrected
            logger.error("Error auto-starting subsystem", e);
        } finally {
            this.lock.writeLock().unlock();
        }
    } else if (event instanceof PropertyBackedBeanStartedEvent) {
        this.lock.writeLock().lock();
        try {
            // If we aren't started, reinitialize so that we pick up state changes from the database
            switch (this.runtimeState) {
            case PENDING_BROADCAST_START:
            case STOPPED:
                destroy(false);
                // fall through
            case UNINITIALIZED:
                start(false, false);
            }
        } finally {
            this.lock.writeLock().unlock();
        }
    } else if (event instanceof PropertyBackedBeanStoppedEvent) {
        this.lock.writeLock().lock();
        try {
            // Completely destroy the state so that it will have to be reinitialized should the bean be put back in
            // to use by this node
            destroy(false);
        } finally {
            this.lock.writeLock().unlock();
        }
    }
}