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

org.graylog.plugins.views.search.searchtypes.pivot.buckets.ValuesBucketOrdering Maven / Gradle / Ivy

There is a newer version: 6.0.1
Show newest version
/*
 * Copyright (C) 2020 Graylog, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Server Side Public License, version 1,
 * as published by MongoDB, Inc.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Server Side Public License for more details.
 *
 * You should have received a copy of the Server Side Public License
 * along with this program. If not, see
 * .
 */
package org.graylog.plugins.views.search.searchtypes.pivot.buckets;

import com.google.common.annotations.VisibleForTesting;
import org.graylog.plugins.views.search.searchtypes.pivot.BucketSpec;
import org.graylog.plugins.views.search.searchtypes.pivot.PivotSort;
import org.graylog.plugins.views.search.searchtypes.pivot.SortSpec;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ValuesBucketOrdering {
    private static boolean isGroupingSort(SortSpec sort) {
        return PivotSort.Type.equals(sort.type());
    }

    private static boolean hasGroupingSort(List sorts) {
        return sorts.stream().anyMatch(ValuesBucketOrdering::isGroupingSort);
    }

    private static boolean needsReorderingFields(List fields, List sorts) {
        return fields.size() >= 2 && !sorts.isEmpty() && hasGroupingSort(sorts);
    }

    public static List orderFields(List fields, List sorts) {
        if (!needsReorderingFields(fields, sorts)) {
            return fields;
        }

        final List sortFields = sorts.stream()
                .filter(ValuesBucketOrdering::isGroupingSort)
                .map(SortSpec::field)
                .collect(Collectors.toList());

        return fields.stream()
                .sorted(new FieldsSortingComparator(sortFields))
                .collect(Collectors.toList());
    }

    public static Function, List> reorderFieldsFunction(List fields, List sorts) {
        if (!needsReorderingFields(fields, sorts)) {
            return Function.identity();
        }

        final List orderedBuckets = orderFields(fields, sorts);
        final Map mapping = IntStream.range(0, fields.size())
                .boxed()
                .collect(Collectors.toMap(Function.identity(), i -> orderedBuckets.indexOf(fields.get(i))));

        return (keys) -> IntStream.range(0, fields.size())
                .boxed()
                .map(i -> keys.get(mapping.get(i)))
                .collect(Collectors.toList());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy