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;
022
023import org.eclipse.aether.collection.DependencyCollectionContext;
024import org.eclipse.aether.collection.VersionFilter;
025import org.eclipse.aether.version.Version;
026
027/**
028 * A version filter that excludes any version except the highest one.
029 */
030public final class HighestVersionFilter implements VersionFilter {
031    private final int count;
032
033    /**
034     * Creates a new instance of this version filter.
035     */
036    public HighestVersionFilter() {
037        this.count = 1;
038    }
039
040    /**
041     * Creates a new instance of this version filter.
042     */
043    public HighestVersionFilter(int count) {
044        if (count < 1) {
045            throw new IllegalArgumentException("Count should be greater or equal to 1");
046        }
047        this.count = count;
048    }
049
050    @Override
051    public void filterVersions(VersionFilterContext context) {
052        if (context.getCount() <= count) {
053            return;
054        }
055        // iterator comes in ascending order, basically we "step over" (remove) first few
056        int stepOver = context.getCount() - count;
057        Iterator<Version> it = context.iterator();
058        while (it.hasNext()) {
059            it.next();
060            stepOver--;
061            if (stepOver >= 0) {
062                it.remove();
063            }
064        }
065    }
066
067    @Override
068    public VersionFilter deriveChildFilter(DependencyCollectionContext context) {
069        return this;
070    }
071
072    @Override
073    public boolean equals(Object obj) {
074        if (this == obj) {
075            return true;
076        } else if (null == obj || !getClass().equals(obj.getClass())) {
077            return false;
078        }
079        return true;
080    }
081
082    @Override
083    public int hashCode() {
084        return getClass().hashCode();
085    }
086}