summaryrefslogtreecommitdiff
path: root/dicore3/command/src/main/java/io/dico/dicore/command/InheritingContextFilter.java
blob: 0b4875b000eeed7ec1ad472337988b38c913b833 (plain)
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
62
63
64
package io.dico.dicore.command;

import java.util.List;

public abstract class InheritingContextFilter implements IContextFilter {
    private static final String[] emptyStringArray = new String[0];

    private static String[] addParent(String[] path, String parent) {
        String[] out = new String[path.length + 1];
        System.arraycopy(path, 0, out, 1, path.length);
        out[0] = parent;
        return out;
    }

    protected abstract boolean isInherited(IContextFilter filter);

    @Override
    public void filterContext(ExecutionContext context) throws CommandException {
        ICommandAddress address = context.getAddress();

        String[] traversedPath = emptyStringArray;
        do {
            traversedPath = addParent(traversedPath, address.getMainKey());
            address = address.getParent();

            if (address != null && address.hasCommand()) {
                boolean doBreak = true;

                Command command = address.getCommand();
                List<IContextFilter> contextFilterList = command.getContextFilters();
                for (IContextFilter filter : contextFilterList) {
                    if (isInherited(filter)) {
                        if (filter == this) {
                            // do the same for next parent
                            // this method is necessary to keep traversedPath information
                            doBreak = false;
                        } else {
                            filter.filterSubContext(context, traversedPath);
                        }
                    }
                }

                if (doBreak) {
                    break;
                }
            }
        } while (address != null);
    }

    static InheritingContextFilter inheritingPriority(Priority priority) {
        return new InheritingContextFilter() {
            @Override
            protected boolean isInherited(IContextFilter filter) {
                return filter.getPriority() == priority;
            }

            @Override
            public Priority getPriority() {
                return priority;
            }
        };
    }

}