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.graph.version;
020
021import java.util.Iterator;
022import java.util.Objects;
023import java.util.function.Predicate;
024
025import org.eclipse.aether.artifact.Artifact;
026import org.eclipse.aether.collection.DependencyCollectionContext;
027import org.eclipse.aether.collection.VersionFilter;
028import org.eclipse.aether.version.Version;
029
030import static java.util.Objects.requireNonNull;
031
032/**
033 * A version filter that excludes any version that is blacklisted.
034 *
035 * @since 2.0.0
036 */
037public final class PredicateVersionFilter implements VersionFilter {
038    private final Predicate<Artifact> artifactPredicate;
039
040    /**
041     * Creates a new instance of this version filter.
042     */
043    public PredicateVersionFilter(Predicate<Artifact> artifactPredicate) {
044        this.artifactPredicate = requireNonNull(artifactPredicate);
045    }
046
047    @Override
048    public void filterVersions(VersionFilterContext context) {
049        Artifact dependencyArtifact = context.getDependency().getArtifact();
050        Iterator<Version> it = context.iterator();
051        while (it.hasNext()) {
052            Version version = it.next();
053            if (!artifactPredicate.test(dependencyArtifact.setVersion(version.toString()))) {
054                it.remove();
055            }
056        }
057    }
058
059    @Override
060    public VersionFilter deriveChildFilter(DependencyCollectionContext context) {
061        return this;
062    }
063
064    @Override
065    public boolean equals(Object o) {
066        if (this == o) {
067            return true;
068        }
069        if (o == null || getClass() != o.getClass()) {
070            return false;
071        }
072        PredicateVersionFilter that = (PredicateVersionFilter) o;
073        return Objects.equals(artifactPredicate, that.artifactPredicate);
074    }
075
076    @Override
077    public int hashCode() {
078        return Objects.hash(artifactPredicate);
079    }
080}