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.util.repository;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.eclipse.aether.repository.Authentication;
025import org.eclipse.aether.repository.AuthenticationSelector;
026import org.eclipse.aether.repository.RemoteRepository;
027
028import static java.util.Objects.requireNonNull;
029
030/**
031 * A simple authentication selector that selects authentication based on repository identifiers.
032 */
033public final class DefaultAuthenticationSelector implements AuthenticationSelector {
034
035    private final Map<String, Authentication> repos = new HashMap<>();
036
037    /**
038     * Adds the specified authentication info for the given repository identifier.
039     *
040     * @param id The identifier of the repository to add the authentication for, must not be {@code null}.
041     * @param auth The authentication to add, may be {@code null}.
042     * @return This selector for chaining, never {@code null}.
043     */
044    public DefaultAuthenticationSelector add(String id, Authentication auth) {
045        if (auth != null) {
046            repos.put(id, auth);
047        } else {
048            repos.remove(id);
049        }
050
051        return this;
052    }
053
054    public Authentication getAuthentication(RemoteRepository repository) {
055        requireNonNull(repository, "repository cannot be null");
056        return repos.get(repository.getId());
057    }
058}