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.synccontext.named;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.util.ArrayList;
026import java.util.Map;
027import java.util.concurrent.TimeUnit;
028
029import org.eclipse.aether.RepositorySystemSession;
030import org.eclipse.aether.impl.NamedLockFactorySelector;
031import org.eclipse.aether.named.NamedLockFactory;
032import org.eclipse.aether.spi.locking.LockingInhibitor;
033import org.eclipse.aether.spi.locking.LockingInhibitorFactory;
034import org.eclipse.aether.util.ConfigUtils;
035import org.slf4j.Logger;
036import org.slf4j.LoggerFactory;
037
038import static java.util.Objects.requireNonNull;
039
040/**
041 * Default implementation of {@link NamedLockFactoryAdapterFactory}. This implementation creates new instances of the
042 * adapter on every call. In turn, on shutdown, it will shut down all existing named lock factories. This is merely for
043 * simplicity, to not have to track "used" named lock factories, while it exposes all available named lock factories to
044 * callers.
045 * <p>
046 * Most members and methods of this class are protected. It is meant to be extended in case of need to customize its
047 * behavior. An exception from this are private static methods, mostly meant to provide out of the box
048 * defaults and to be used when no Eclipse Sisu component container is used.
049 *
050 * @since 1.9.1
051 */
052@Singleton
053@Named
054public class NamedLockFactoryAdapterFactoryImpl implements NamedLockFactoryAdapterFactory {
055    public static final String DEFAULT_NAME_MAPPER_NAME = NameMappers.FILE_GAECV_NAME;
056
057    /**
058     * Name of the lock factory to use in session. Out of the box supported ones are "file-lock", "rwlock-local",
059     * "semaphore-local", "noop". By adding extensions one can extend available lock factories (for example IPC locking).
060     * <strong>Deprecated: use {@code aether.system.named...} configuration instead.</strong>
061     *
062     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
063     * @configurationType {@link java.lang.String}
064     * @deprecated
065     */
066    @Deprecated
067    public static final String CONFIG_PROP_FACTORY_KEY = NamedLockFactoryAdapter.CONFIG_PROPS_PREFIX + "factory";
068
069    /**
070     * Name of the name mapper to use in session. Out of the box supported ones are "static", "gav", "gaecv", "file-gav",
071     * "file-gaecv", "file-hgav", "file-hgaecv", "file-static" and "discriminating".
072     *
073     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
074     * @configurationType {@link java.lang.String}
075     * @configurationDefaultValue {@link #DEFAULT_NAME_MAPPER_NAME}
076     */
077    public static final String CONFIG_PROP_NAME_MAPPER_KEY = NamedLockFactoryAdapter.CONFIG_PROPS_PREFIX + "nameMapper";
078
079    protected final Logger logger = LoggerFactory.getLogger(getClass());
080
081    protected final NamedLockFactorySelector namedLockFactorySelector;
082
083    protected final Map<String, NameMapper> nameMappers;
084
085    protected final String defaultNameMapperName;
086
087    protected final Map<String, LockingInhibitorFactory> lockingInhibitorFactories;
088
089    @Inject
090    public NamedLockFactoryAdapterFactoryImpl(
091            final NamedLockFactorySelector namedLockFactorySelector,
092            final Map<String, NameMapper> nameMappers,
093            final Map<String, LockingInhibitorFactory> lockingInhibitorFactories) {
094        this(namedLockFactorySelector, nameMappers, DEFAULT_NAME_MAPPER_NAME, lockingInhibitorFactories);
095    }
096
097    public NamedLockFactoryAdapterFactoryImpl(
098            final NamedLockFactorySelector namedLockFactorySelector,
099            final Map<String, NameMapper> nameMappers,
100            final String defaultNameMapperName,
101            final Map<String, LockingInhibitorFactory> lockingInhibitorFactories) {
102        this.namedLockFactorySelector = requireNonNull(namedLockFactorySelector);
103        this.nameMappers = requireNonNull(nameMappers);
104        this.defaultNameMapperName = requireNonNull(defaultNameMapperName);
105        this.lockingInhibitorFactories = requireNonNull(lockingInhibitorFactories);
106
107        logger.debug(
108                "Created adapter factory; available lock factories {}; available name mappers {}",
109                namedLockFactorySelector.getAvailableLockFactories(),
110                nameMappers.keySet());
111    }
112
113    private static final String ADAPTER_KEY = NamedLockFactoryAdapterFactoryImpl.class.getName() + ".adapter";
114
115    /**
116     * Current implementation memoize instance in session or delegates to {@link #createAdapter(RepositorySystemSession)}.
117     */
118    @Override
119    public NamedLockFactoryAdapter getAdapter(RepositorySystemSession session) {
120        requireNonNull(session, "session cannot be null");
121        return (NamedLockFactoryAdapter) session.getData().computeIfAbsent(ADAPTER_KEY, () -> createAdapter(session));
122    }
123
124    /**
125     * Creates a new adapter instance, never returns {@code null}.
126     */
127    protected NamedLockFactoryAdapter createAdapter(RepositorySystemSession session) {
128        final NameMapper nameMapper = selectNameMapper(session, requireNonNull(getNameMapperName(session)));
129        final NamedLockFactory factory = namedLockFactorySelector.getNamedLockFactory(session.getConfigProperties());
130        final long lockWait = namedLockFactorySelector.getLockWaitTime(session.getConfigProperties());
131        final TimeUnit lockWaitUnit = namedLockFactorySelector.getLockWaitTimeUnit(session.getConfigProperties());
132        logger.debug("Creating adapter using nameMapper '{}' and factory '{}'", nameMapper, factory);
133        return new NamedLockFactoryAdapter(nameMapper, factory, lockWait, lockWaitUnit);
134    }
135
136    /**
137     * Returns the selected (user configured or default) name mapper name, never {@code null}.
138     */
139    protected String getNameMapperName(RepositorySystemSession session) {
140        return ConfigUtils.getString(session, getDefaultNameMapperName(), CONFIG_PROP_NAME_MAPPER_KEY);
141    }
142
143    /**
144     * Returns the default name mapper name, never {@code null}.
145     */
146    protected String getDefaultNameMapperName() {
147        return defaultNameMapperName;
148    }
149
150    /**
151     * Selects a name mapper, never returns {@code null}. Applies inhibitors.
152     */
153    protected NameMapper selectNameMapper(final RepositorySystemSession session, final String nameMapperName) {
154        NameMapper nameMapper = nameMappers.get(nameMapperName);
155        if (nameMapper == null) {
156            throw new IllegalArgumentException(
157                    "Unknown NameMapper name: '" + nameMapperName + "', known ones: " + nameMappers.keySet());
158        }
159        if (!lockingInhibitorFactories.isEmpty()) {
160            ArrayList<LockingInhibitor> inhibitors = new ArrayList<>();
161            for (LockingInhibitorFactory factory : lockingInhibitorFactories.values()) {
162                factory.newInstance(session).ifPresent(inhibitors::add);
163            }
164            if (!inhibitors.isEmpty()) {
165                return new InhibitingNameMapper(nameMapper, inhibitors);
166            }
167        }
168        return nameMapper;
169    }
170}