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.collection.DependencyCollectionContext;
026import org.eclipse.aether.collection.VersionFilter;
027import org.eclipse.aether.version.Version;
028
029import static java.util.Objects.requireNonNull;
030
031/**
032 * A version filter that excludes any version that is blacklisted.
033 *
034 * @since 2.0.11
035 */
036public class VersionPredicateVersionFilter implements VersionFilter {
037    private final Predicate<Version> versionPredicate;
038
039    /**
040     * Creates a new instance of this version filter. It will filter out versions not matched by predicate.
041     * Note: filter always operates with baseVersions.
042     */
043    public VersionPredicateVersionFilter(Predicate<Version> versionPredicate) {
044        this.versionPredicate = requireNonNull(versionPredicate);
045    }
046
047    @Override
048    public void filterVersions(VersionFilterContext context) {
049        for (Iterator<Version> it = context.iterator(); it.hasNext(); ) {
050            if (!versionPredicate.test(it.next())) {
051                it.remove();
052            }
053        }
054    }
055
056    @Override
057    public VersionFilter deriveChildFilter(DependencyCollectionContext context) {
058        return this;
059    }
060
061    @Override
062    public boolean equals(Object o) {
063        if (this == o) {
064            return true;
065        }
066        if (o == null || getClass() != o.getClass()) {
067            return false;
068        }
069        VersionPredicateVersionFilter that = (VersionPredicateVersionFilter) o;
070        return Objects.equals(versionPredicate, that.versionPredicate);
071    }
072
073    @Override
074    public int hashCode() {
075        return getClass().hashCode();
076    }
077}