001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012package org.nuxeo.ecm.core.opencmis.bindings;
013
014import javax.servlet.ServletContextEvent;
015import javax.servlet.ServletContextListener;
016
017import org.apache.chemistry.opencmis.commons.server.CmisServiceFactory;
018import org.apache.chemistry.opencmis.server.impl.CmisRepositoryContextListener;
019import org.nuxeo.runtime.RuntimeService;
020import org.nuxeo.runtime.RuntimeServiceEvent;
021import org.nuxeo.runtime.RuntimeServiceListener;
022import org.nuxeo.runtime.api.Framework;
023
024/**
025 * Servlet context listener that sets up the CMIS service factory in the servlet context as expected by
026 * {@link org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet} or
027 * {@link org.apache.chemistry.opencmis.server.impl.browser.CmisBrowserBindingServlet} or
028 * {@link org.apache.chemistry.opencmis.server.impl.webservices.AbstractService} .
029 *
030 * @see CmisRepositoryContextListener
031 */
032public class NuxeoCmisContextListener implements ServletContextListener {
033
034    @Override
035    public void contextInitialized(final ServletContextEvent sce) {
036        RuntimeService runtime = Framework.getRuntime();
037        if (runtime == null || !runtime.isStarted()) {
038            Framework.addListener(new RuntimeServiceListener() {
039
040                @Override
041                public void handleEvent(RuntimeServiceEvent event) {
042                    if (event.id != RuntimeServiceEvent.RUNTIME_STARTED) {
043                        return;
044                    }
045                    Framework.removeListener(this);
046                    activate(sce);
047                }
048
049            });
050        } else {
051            activate(sce);
052        }
053    }
054
055    protected void activate(final ServletContextEvent sce) {
056        NuxeoCmisServiceFactoryManager manager = Framework.getService(NuxeoCmisServiceFactoryManager.class);
057        CmisServiceFactory factory = manager.getNuxeoCmisServiceFactory();
058        sce.getServletContext().setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory);
059    }
060
061    @Override
062    public void contextDestroyed(ServletContextEvent sce) {
063        CmisServiceFactory factory = (CmisServiceFactory) sce.getServletContext().getAttribute(
064                CmisRepositoryContextListener.SERVICES_FACTORY);
065        if (factory != null) {
066            factory.destroy();
067        }
068    }
069
070}