aboutsummaryrefslogtreecommitdiff
path: root/src/cz/crcs/ectester/standalone/consts/Ident.java
blob: 29603c2e2d01d4e8fa786bc6bbf1038a31383f52 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package cz.crcs.ectester.standalone.consts;

import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiFunction;

public abstract class Ident {
    Set<String> idents;
    String name;

    public Ident(String name, String... aliases) {
        this.name = name;
        this.idents = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        this.idents.add(name);
        this.idents.addAll(Arrays.asList(aliases));
    }

    public String getName() {
        return name;
    }

    public Set<String> getIdents() {
        return Collections.unmodifiableSet(idents);
    }

    public boolean contains(String other) {
        return name.equals(other) || idents.contains(other);
    }

    <T> T getInstance(BiFunction<String, Provider, T> getter, Provider provider) throws NoSuchAlgorithmException {
        T instance = null;
        try {
            instance = getter.apply(name, provider);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }

        if (instance == null) {
            for (String alias : idents) {
                try {
                    instance = getter.apply(alias, provider);
                    if (instance != null) {
                        break;
                    }
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        }

        if (instance == null) {
            throw new NoSuchAlgorithmException(name);
        }
        return instance;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Ident)) {
            return false;
        }
        Ident other = (Ident) obj;
        return idents.equals(other.getIdents());
    }

    @Override
    public int hashCode() {
        return idents.hashCode() + 37;
    }

    @Override
    public String toString() {
        return "(" + String.join("|", idents) + ")";
    }
}