aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/pagetemplates/engine/SourceOrderComparator.java
blob: 65642b7e8bce3e23eabe93d6daa3c119eae88825 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.pagetemplates.engine;

import com.yahoo.search.result.ChainableComparator;
import com.yahoo.search.result.Hit;

import java.util.Comparator;
import java.util.List;

/**
 * @author bratseth
 */
class SourceOrderComparator extends ChainableComparator {

    private final List<String> sourceOrder;

    /**
     * Creates a source order comparator, with no secondary
     *
     * @param sourceOrder the sort order of list names. This list gets owned by this and must not be modified
     */
    public SourceOrderComparator(List<String> sourceOrder) {
        this(sourceOrder,null);
    }

    /**
     * Creates a source order comparator, with an optional secondary comparator.
     *
     * @param sourceOrder the sort order of list names. This list gets owned by this and must not be modified
     * @param secondaryComparator the comparator to use as secondary, or null to use the intrinsic hit order
     */
    public SourceOrderComparator(List<String> sourceOrder,Comparator<Hit> secondaryComparator) {
        super(secondaryComparator);
        this.sourceOrder=sourceOrder;
    }

    @Override
    public int compare(Hit h1,Hit h2) {
        int primaryOrder=sourceOrderCompare(h1,h2);
        if (primaryOrder!=0) return primaryOrder;

        return super.compare(h1,h2);
    }

    private int sourceOrderCompare(Hit h1,Hit h2) {
        String h1Source=h1.getSource();
        String h2Source=h2.getSource();

        if (h1Source==null && h2Source==null) return 0;
        if (h1Source==null) return 1; // No source -> last
        if (h2Source==null) return -1; // No source -> last

        if (h1Source.equals(h2Source)) return 0;

        return sourceOrder.indexOf(h1Source)-sourceOrder.indexOf(h2Source);
    }

}