All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.gradle.api.internal.collections.CollectionFilter Maven / Gradle / Ivy

There is a newer version: 8.6
Show newest version
/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gradle.api.internal.collections;

import org.gradle.api.Action;
import org.gradle.api.specs.Spec;
import org.gradle.api.specs.Specs;

public class CollectionFilter implements Spec {

    private Class type;
    private Spec spec;

    public CollectionFilter(Class type) {
        this(type, Specs.satisfyAll());
    }

    public CollectionFilter(Class type, Spec spec) {
        this.type = type;
        this.spec = spec;
    }

    public Class getType() {
        return type;
    }

    public T filter(Object object) {
        if (!type.isInstance(object)) {
            return null;
        }

        T t = type.cast(object);
        if (spec.isSatisfiedBy(t)) {
            return t;
        } else {
            return null;
        }
    }

    public Action filtered(final Action action) {
        return new Action() {
            @Override
            public void execute(Object o) {
                T t = filter(o);
                if (t != null) {
                    action.execute(t);
                }
            }
        };
    }

    public boolean isSatisfiedBy(Object element) {
        return filter(element) != null;
    }

    @SuppressWarnings("unchecked")
    public  CollectionFilter and(CollectionFilter other) {
        return new CollectionFilter(other.type, Specs.intersect(spec, other.spec));
    }
}