summaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditor.java
blob: d687f959d3b35ff500b349c570ad301c00f7713b (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
59
60
61
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.acl;

import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Acl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.LineEdit;
import com.yahoo.vespa.hosted.node.admin.task.util.file.LineEditor;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;

import java.util.List;

/**
 * An editor that assumes all rules in the filter table are exactly as the wanted rules
 *
 * @author smorgrav
 */
class FilterTableLineEditor implements LineEditor {

    private final List<String> wantedRules;
    private int position = 0;

    private FilterTableLineEditor(List<String> wantedRules) {
        this.wantedRules = List.copyOf(wantedRules);
    }

    static FilterTableLineEditor from(Acl acl, IPVersion ipVersion) {
        List<String> rules = acl.toRules(ipVersion);
        return new FilterTableLineEditor(rules);
    }

    @Override
    public LineEdit edit(String line) {
        int index = indexOf(wantedRules, line, position);
        // Unwanted rule, remove
        if (index < 0) return LineEdit.remove();

        // Wanted rule at the expected position, no diff
        if (index == position) {
            position++;
            return LineEdit.none();
        }

        // Insert the rules between position and index before index
        List<String> toInsert = wantedRules.subList(position, index);
        position = ++index;
        return LineEdit.insertBefore(toInsert);
    }

    @Override
    public List<String> onComplete() {
        return wantedRules.subList(position, wantedRules.size());
    }

    private static <T> int indexOf(List<T> list, T value, int startPos) {
        for (int i = startPos; i < list.size(); i++) {
            if (value.equals(list.get(i)))
                return i;
        }

        return -1;
    }
}