001/*
002 * (C) Copyright 2015-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 *     Stephane Lacoin
018 */
019package org.nuxeo.webengine.gwt.codeserver;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.nuxeo.ecm.core.api.NuxeoException;
025import org.nuxeo.runtime.model.ComponentContext;
026import org.nuxeo.runtime.model.ComponentInstance;
027import org.nuxeo.runtime.model.DefaultComponent;
028
029public class CodeServerComponent extends DefaultComponent {
030
031    final Map<String, CodeServerConfig> servers = new HashMap<>();
032
033    @Override
034    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
035        if (contribution instanceof CodeServerConfig) {
036            CodeServerConfig install = (CodeServerConfig) contribution;
037            servers.put(install.module, install);
038        }
039    }
040
041    @Override
042    public void start(ComponentContext context) {
043        startup();
044    }
045
046    @Override
047    public void stop(ComponentContext context) {
048        shutdown();
049    }
050
051    protected void startup() {
052        new Runner() {
053
054            @Override
055            void doRun(CodeServerConfig server) throws Exception {
056                server.startup();
057            }
058
059        }.run();
060    }
061
062    protected void shutdown() {
063        new Runner() {
064
065            @Override
066            void doRun(CodeServerConfig server) throws Exception {
067                server.shutdown();
068            }
069
070        }.run();
071    }
072
073    abstract class Runner {
074
075        void run() {
076            NuxeoException errors = new NuxeoException("Cannot shudown gwt code servers");
077            for (CodeServerConfig server : servers.values()) {
078                try {
079                    doRun(server);
080                } catch (Exception cause) {
081                    errors.addSuppressed(cause);
082                }
083            }
084            if (errors.getSuppressed().length > 0) {
085                throw errors;
086            }
087        }
088
089        abstract void doRun(CodeServerConfig server) throws Exception;
090    }
091
092}