001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.io.comparator;
018
019import java.io.File;
020import java.io.Serializable;
021import java.util.Comparator;
022import java.util.function.IntFunction;
023import java.util.stream.Stream;
024import java.util.stream.StreamSupport;
025
026/**
027 * Compare two files using a set of delegate file {@link Comparator}.
028 * <p>
029 * This comparator can be used to sort lists or arrays of files by combining a number of other comparators.
030 * <p>
031 * Example of sorting a list of files by type (i.e. directory or file) and then by name:
032 *
033 * <pre>
034 *       CompositeFileComparator comparator = new CompositeFileComparator(
035 *           DirectoryFileComparator.DIRECTORY_COMPARATOR,
036 *           NameFileComparator.NAME_COMPARATOR);
037 *       List&lt;File&gt; list = ...
038 *       comparator.sort(list);
039 * </pre>
040 * <h2>Deprecating Serialization</h2>
041 * <p>
042 * <em>Serialization is deprecated and will be removed in 3.0.</em>
043 * </p>
044 *
045 * @since 2.0
046 */
047public class CompositeFileComparator extends AbstractFileComparator implements Serializable {
048
049    private static final Comparator<?>[] EMPTY_COMPARATOR_ARRAY = {};
050    private static final long serialVersionUID = -2224170307287243428L;
051
052    /**
053     * Delegates.
054     */
055    private final Comparator<File>[] delegates;
056
057    /**
058     * Constructs a composite comparator for the set of delegate comparators.
059     *
060     * @param delegates The delegate file comparators
061     */
062    public CompositeFileComparator(@SuppressWarnings("unchecked") final Comparator<File>... delegates) {
063        this.delegates = delegates == null ? emptyArray() : delegates.clone();
064    }
065
066    /**
067     * Constructs a composite comparator for the set of delegate comparators.
068     *
069     * @param delegates The delegate file comparators
070     */
071    public CompositeFileComparator(final Iterable<Comparator<File>> delegates) {
072        this.delegates = delegates == null ? emptyArray()
073                : StreamSupport.stream(delegates.spliterator(), false).toArray((IntFunction<Comparator<File>[]>) Comparator[]::new);
074    }
075
076    /**
077     * Compares the two files using delegate comparators.
078     *
079     * @param file1 The first file to compare
080     * @param file2 The second file to compare
081     * @return the first non-zero result returned from the delegate comparators or zero.
082     */
083    @Override
084    public int compare(final File file1, final File file2) {
085        return Stream.of(delegates).map(delegate -> delegate.compare(file1, file2)).filter(r -> r != 0).findFirst().orElse(0);
086    }
087
088    @SuppressWarnings("unchecked") // types are already correct
089    private Comparator<File>[] emptyArray() {
090        return (Comparator<File>[]) EMPTY_COMPARATOR_ARRAY;
091    }
092
093    /**
094     * String representation of this file comparator.
095     *
096     * @return String representation of this file comparator
097     */
098    @Override
099    public String toString() {
100        final StringBuilder builder = new StringBuilder();
101        builder.append(super.toString());
102        builder.append('{');
103        for (int i = 0; i < delegates.length; i++) {
104            if (i > 0) {
105                builder.append(',');
106            }
107            builder.append(delegates[i]);
108        }
109        builder.append('}');
110        return builder.toString();
111    }
112}