001/*
002 * (C) Copyright 2006-2017 Nuxeo (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 *     bstefanescu
018 */
019package org.nuxeo.runtime.model.impl;
020
021import java.util.Set;
022
023import org.nuxeo.runtime.model.ComponentManager;
024import org.nuxeo.runtime.model.ComponentName;
025import org.nuxeo.runtime.model.RegistrationInfo;
026
027/**
028 * Deactivate components in the proper order to avoid exceptions at shutdown.
029 *
030 * @deprecated since 9.2, it is useless to unregister components. Components are stopped and deactivated by the
031 *             {@link ComponentManager#stop()}
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034@Deprecated
035public class ShutdownTask {
036
037    final static void shutdown(ComponentManagerImpl mgr) {
038        RegistrationInfoImpl[] ris = mgr.registry.getComponentsArray();
039        for (RegistrationInfoImpl ri : ris) {
040            shutdown(mgr, ri);
041        }
042    }
043
044    private static void shutdown(ComponentManagerImpl mgr, RegistrationInfoImpl ri) {
045        ComponentName name = ri.getName();
046        if (name == null) {
047            return; // already destroyed
048        }
049        if (ri.getState() <= RegistrationInfo.RESOLVED) {
050            // not yet activated so we can destroy it right now
051            mgr.unregister(name);
052            return;
053        }
054        // an active component - get the components depending on it
055        Set<ComponentName> reqs = mgr.registry.requirements.get(name);
056        if (reqs != null && !reqs.isEmpty()) {
057            // there are some components depending on me - cannot shutdown
058            for (ComponentName req : reqs.toArray(new ComponentName[reqs.size()])) {
059                RegistrationInfoImpl parentRi = mgr.registry.components.get(req);
060                if (parentRi != null) {
061                    shutdown(mgr, parentRi);
062                }
063            }
064        }
065        // no components are depending on me - shutdown now
066        mgr.unregister(name);
067    }
068
069}