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.selector;
020
021import org.eclipse.aether.collection.DependencyCollectionContext;
022import org.eclipse.aether.collection.DependencySelector;
023import org.eclipse.aether.graph.Dependency;
024
025import static java.util.Objects.requireNonNull;
026
027/**
028 * A dependency selector that excludes optional dependencies which occur beyond level one of the dependency graph.
029 *
030 * @see Dependency#isOptional()
031 */
032public final class OptionalDependencySelector implements DependencySelector {
033
034    private final int depth;
035
036    /**
037     * Creates a new selector to exclude optional transitive dependencies.
038     */
039    public OptionalDependencySelector() {
040        depth = 0;
041    }
042
043    private OptionalDependencySelector(int depth) {
044        this.depth = depth;
045    }
046
047    public boolean selectDependency(Dependency dependency) {
048        requireNonNull(dependency, "dependency cannot be null");
049        return depth < 2 || !dependency.isOptional();
050    }
051
052    public DependencySelector deriveChildSelector(DependencyCollectionContext context) {
053        requireNonNull(context, "context cannot be null");
054        if (depth >= 2) {
055            return this;
056        }
057
058        return new OptionalDependencySelector(depth + 1);
059    }
060
061    @Override
062    public boolean equals(Object obj) {
063        if (this == obj) {
064            return true;
065        } else if (null == obj || !getClass().equals(obj.getClass())) {
066            return false;
067        }
068
069        OptionalDependencySelector that = (OptionalDependencySelector) obj;
070        return depth == that.depth;
071    }
072
073    @Override
074    public int hashCode() {
075        int hash = getClass().hashCode();
076        hash = hash * 31 + depth;
077        return hash;
078    }
079
080    @Override
081    public String toString() {
082        return String.format("%s(depth: %d)", this.getClass().getSimpleName(), this.depth);
083    }
084}