001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.impl;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.util.ArrayList;
026import java.util.concurrent.CopyOnWriteArrayList;
027import java.util.concurrent.atomic.AtomicBoolean;
028
029import org.eclipse.aether.MultiRuntimeException;
030import org.eclipse.aether.impl.RepositorySystemLifecycle;
031
032import static java.util.Objects.requireNonNull;
033
034/**
035 *
036 */
037@Singleton
038@Named
039public class DefaultRepositorySystemLifecycle implements RepositorySystemLifecycle {
040    private final AtomicBoolean shutdown;
041
042    private final CopyOnWriteArrayList<Runnable> onSystemEndedHandlers;
043
044    @Inject
045    public DefaultRepositorySystemLifecycle() {
046        this.shutdown = new AtomicBoolean(false);
047        this.onSystemEndedHandlers = new CopyOnWriteArrayList<>();
048    }
049
050    @Override
051    public void systemEnded() {
052        if (shutdown.compareAndSet(false, true)) {
053            final ArrayList<Exception> exceptions = new ArrayList<>();
054            for (Runnable onCloseHandler : onSystemEndedHandlers) {
055                try {
056                    onCloseHandler.run();
057                } catch (Exception e) {
058                    exceptions.add(e);
059                }
060            }
061            MultiRuntimeException.mayThrow("system on-close handler failures", exceptions);
062        }
063    }
064
065    @Override
066    public void addOnSystemEndedHandler(Runnable handler) {
067        requireNonNull(handler, "handler cannot be null");
068        requireNotShutdown();
069        onSystemEndedHandlers.add(0, handler);
070    }
071
072    private void requireNotShutdown() {
073        if (shutdown.get()) {
074            throw new IllegalStateException("repository system is already shut down");
075        }
076    }
077}