001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.platform.ui.web.application.config;
020
021import javax.servlet.ServletContextEvent;
022import javax.servlet.ServletContextListener;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.runtime.RuntimeServiceEvent;
027import org.nuxeo.runtime.RuntimeServiceListener;
028import org.nuxeo.runtime.api.Framework;
029
030import com.sun.faces.config.ConfigureListener;
031
032/**
033 * Handles JSF configuration at startup.
034 * <p>
035 * Delays configuration until runtime is initialized to handle correctly dev mode.
036 *
037 * @since 6.0
038 */
039public class JSFConfigureListener implements ServletContextListener, RuntimeServiceListener {
040
041    private static final Log log = LogFactory.getLog(JSFConfigureListener.class);
042
043    protected ConfigureListener confListener;
044
045    protected ServletContextEvent origEvent;
046
047    @Override
048    public void contextInitialized(ServletContextEvent sce) {
049        origEvent = sce;
050        confListener = new ConfigureListener();
051        confListener.contextInitialized(sce);
052        Framework.addListener(this);
053    }
054
055    @Override
056    public void contextDestroyed(ServletContextEvent sce) {
057        confListener.contextDestroyed(sce);
058        Framework.removeListener(this);
059    }
060
061    @Override
062    public void handleEvent(RuntimeServiceEvent event) {
063        if (event.id == RuntimeServiceEvent.RUNTIME_STARTED) {
064            // reload app to make sure dev mode is taken into account by
065            // facelets cache factory
066            reload();
067            Framework.removeListener(this);
068        }
069    }
070
071    protected void reload() {
072        if (log.isDebugEnabled()) {
073            log.debug("Reloading JSF configuration");
074        }
075        if (Framework.isDevModeSet() && confListener != null) {
076            confListener.contextDestroyed(origEvent);
077            confListener.contextInitialized(origEvent);
078        }
079    }
080
081}