summaryrefslogtreecommitdiff
path: root/dicore3/core/src/main/java/io/dico/dicore/SetBasedWhitelist.java
blob: d4486edb4dc57196d8322aea6b0f8d926cffaefc (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
package io.dico.dicore;

import org.bukkit.configuration.ConfigurationSection;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SetBasedWhitelist implements Whitelist {
    private final Set set;
    private final boolean blacklist;
    
    public SetBasedWhitelist(Object[] array, boolean blacklist) {
        this(Arrays.asList(array), blacklist);
    }
    
    public SetBasedWhitelist(ConfigurationSection section, Function<String, ?> parser) {
        this(section.getStringList("listed").stream().map(parser).filter(Objects::nonNull).collect(Collectors.toList()),
                section.getBoolean("blacklist", false));
    }
    
    @SuppressWarnings("unchecked")
    public SetBasedWhitelist(Collection collection, boolean blacklist) {
        Set set;
        if (collection.isEmpty()) {
            set = Collections.emptySet();
        } else if (collection.iterator().next() instanceof Enum) {
            set = EnumSet.copyOf(collection);
        } else if (collection instanceof Set) {
            set = (Set) collection;
        } else {
            set = new HashSet<>(collection);
        }
        
        this.set = set;
        this.blacklist = blacklist;
    }
    
    @Override
    public boolean isWhitelisted(Object o) {
        return blacklist != set.contains(o);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public String toString() {
        return (blacklist ? "Blacklist" : "Whitelist") + "{"
                + String.join(", ", (CharSequence[]) set.stream().map(String::valueOf).toArray(String[]::new)) + "}";
    }
    
    public Set getSet() {
        return set;
    }
    
    public boolean isBlacklist() {
        return blacklist;
    }
    
}