aboutsummaryrefslogtreecommitdiffstats
path: root/component/src/main/java/com/yahoo/component/ComponentId.java
blob: 7320d24b57c3dc5ff9854052f33b9fd50843a79e (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * The id of a component.
 * Consists of a name, optionally a version, and optionally a namespace.
 * This is an immutable value object.
 *
 * @author bratseth
 * @author Tony Vaagenes
 */
public final class ComponentId implements Comparable<ComponentId> {

    private final Spec<Version> spec;
    private final boolean anonymous;

    private static AtomicInteger threadIdCounter = new AtomicInteger(0);

    private static ThreadLocal<Counter> threadLocalUniqueId = new ThreadLocal<Counter>() {
        @Override protected Counter initialValue() {
            return new Counter();
        }
    };

    private static ThreadLocal<String> threadId = new ThreadLocal<String>() {
        @Override protected String initialValue() {
            return new String("_" + threadIdCounter.getAndIncrement() + "_");
        }
    };

    /** Precomputed string value */
    private final String stringValue;

    /**
     * Creates a component id from the id string form: name(:version)?(@namespace)?,
     * where version has the form 1(.2(.3(.identifier)?)?)?
     * and namespace is a component id
     */
    public ComponentId(String id) {
        this(new SpecSplitter(id));
    }

    private ComponentId(SpecSplitter splitter) {
        this(splitter.name, Version.fromString(splitter.version), splitter.namespace);
    }

    public ComponentId(String name, Version version, ComponentId namespace) {
        this(name, version, namespace, false);
    }

    /** Creates a component id from a name and version. The version may be null */
    public ComponentId(String name, Version version) {
        this(name, version, null);
    }

    private ComponentId(String id, Version version, ComponentId namespace, boolean anonymous) {
        this.spec = new Spec<>(new VersionHandler(), id, version, namespace);
        this.anonymous = anonymous;
        this.stringValue = spec.createStringValue();
    }

    public ComponentId nestInNamespace(ComponentId namespace) {
        if (namespace == null) {
            return this;
        } else {
            ComponentId newNamespace = (getNamespace() == null)
                    ? namespace
                    : getNamespace().nestInNamespace(namespace);
            return new ComponentId(getName(), getVersion(), newNamespace);
        }
    }

    /** Returns the name of this. This is never null */
    public String getName() { return spec.name; }

    /** Returns the version of this id, or emptyVersion if no version is specified */
    public Version getVersion() { return spec.version; }

    /** The namespace is null if this is a top level component id **/
    public ComponentId getNamespace() { return spec.namespace; }

    /**
     * Returns the string value of this id.
     * If no version is given, this is simply the name.
     * If a version is given, it is name:version.
     * Trailing ".0"'s are stripped from the version part.
     */
    public String stringValue() { return stringValue; }

    @Override
    public String toString() {
        return spec.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if ( ! (o instanceof ComponentId)) return false;

        ComponentId c = (ComponentId) o;
        if (isAnonymous() || c.isAnonymous()) // TODO: Stop doing this
            return false;

        return c.stringValue().equals(stringValue);
    }

    @Override
    public int hashCode() {
        return stringValue.hashCode();
    }

    public ComponentSpecification toSpecification() {
        if (isAnonymous())
            throw new RuntimeException("Can't generate a specification for an anonymous component id.");
        return new ComponentSpecification(getName(),
                getVersion().toSpecification(), getNamespace());
    }

    public int compareTo(ComponentId other) {
        //anonymous must never be equal to non-anonymous
        if (isAnonymous() ^ other.isAnonymous()) {
            return isAnonymous() ? -1 : 1;
        }

        return spec.compareTo(other.spec);
    }

    /** Creates a componentId that is unique for this run-time instance */
    public static ComponentId createAnonymousComponentId(String baseName) {
        return new ComponentId(createAnonymousId(baseName), null, null, true);
    }

    public boolean isAnonymous() {
        return anonymous;
    }

    /** Returns a copy of this id with namespace set to null **/
    public ComponentId withoutNamespace() {
        return new ComponentId(getName(), getVersion(), null);
    }

    /**
     * Creates a component id from the id string form: name(:version)?(@namespace)?,
     * where version has the form 1(.2(.3(.identifier)?)?)?
     * and namespace is a component id.
     *
     * @return new ComponentId(componentId), or null if the input string is null
     */
    public static ComponentId fromString(String componentId) {
        try {
            return (componentId != null) ? new ComponentId(componentId) : null;
        } catch(Exception e) {
            throw new IllegalArgumentException("Illegal component id: '" + componentId + "'", e);
        }
    }

    /**
     * Returns this id's stringValue (i.e the id without trailing ".0"'s) translated to a file name using the
     * <i>standard translation:</i>
     * <pre><code>
     *     : → -
     *     / → _
     * </code></pre>
     */
    public String toFileName() {
        return stringValue.replace(":","-").replace("/",".");
    }

    /**
     * Creates an id from a file <b>first</b> name string encoded in the standard translation (see {@link #toFileName}).
     * <b>Note</b> that any file last name, like e.g ".xml" must be stripped off before handoff to this method.
     */
    public static ComponentId fromFileName(String fileName) {
        // Initial assumptions
        String id = fileName;
        Version version = null;
        ComponentId namespace = null;

        // Split out namespace, if any
        int at = id.indexOf("@");
        if (at > 0) {
            String newId = id.substring(0, at);
            namespace = ComponentId.fromString(id.substring(at + 1));
            id = newId;
        }

        // Split out version, if any
        int dash = id.lastIndexOf("-");
        if (dash > 0) {
            String newId = id.substring(0, dash);
            try {
                version = new Version(id.substring(dash + 1));
                id = newId;
            }
            catch (IllegalArgumentException e) {
                // don't interpret the text following the dash as a version
            }
        }

        // Convert dots in id portion back - this is the part which prevents us from
        id=id.replace(".","/");

        return new ComponentId(id,version,namespace);
    }

    /** WARNING: For testing only: Resets counters creating anonymous component ids for this thread. */
    public static void resetGlobalCountersForTests() {
        threadId.set("_0_");
        threadLocalUniqueId.set(new Counter());
    }

    private static String createAnonymousId(String name) {
        return name + threadId.get() + threadLocalUniqueId.get().getAndIncrement();
    }

    /** Creates a component id with the given value, marked as anonymous */
    public static ComponentId newAnonymous(String spec) {
        var splitter = new SpecSplitter(spec);
        return new ComponentId(splitter.name, Version.fromString(splitter.version), splitter.namespace, true);
    }

    private final class VersionHandler implements Spec.VersionHandler<Version> {

        @Override
        public Version emptyVersion() {
            return Version.emptyVersion;
        }

        @Override
        public int compare(Version v1, Version v2) {
            return v1.compareTo(v2);
        }

    }

    private final static class Counter {

        private int count = 0;
        public int getAndIncrement() { return count++; }

    }

}