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