This repository was archived by the owner on May 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathTemplatedResourceName.java
More file actions
290 lines (253 loc) · 9.4 KB
/
TemplatedResourceName.java
File metadata and controls
290 lines (253 loc) · 9.4 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
* Copyright 2016, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.pathtemplate;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* Class for representing and working with resource names.
*
* <p>A resource name is represented by {@link PathTemplate}, an assignment to variables in the
* template, and an optional endpoint. The {@code ResourceName} class implements the map interface
* (unmodifiable) to work with the variable assignments, and has methods to reproduce the string
* representation of the name, to construct new names, and to dereference names into resources.
*
* <p>As a resource name essentially represents a match of a path template against a string, it can
* be also used for other purposes than naming resources. However, not all provided methods may make
* sense in all applications.
*
* <p>Usage examples:
*
* <pre>{@code
* PathTemplate template = PathTemplate.create("shelves/*/books/*");
* TemplatedResourceName resourceName = TemplatedResourceName.create(template, "shelves/s1/books/b1");
* assert resourceName.get("$1").equals("b1");
* assert resourceName.parentName().toString().equals("shelves/s1/books");
* }</pre>
*/
public class TemplatedResourceName implements Map<String, String> {
// ResourceName Resolver
// =====================
/** Represents a resource name resolver which can be registered with this class. */
public interface Resolver {
/** Resolves the resource name into a resource by calling the underlying API. */
<T> T resolve(Class<T> resourceType, TemplatedResourceName name, @Nullable String version);
}
// The registered resource name resolver.
// TODO(wrwg): its a bit spooky to have this static global. Think of ways to
// configure this from the outside instead if programmatically (e.g. java properties).
private static volatile Resolver resourceNameResolver =
new Resolver() {
@Override
public <T> T resolve(Class<T> resourceType, TemplatedResourceName name, String version) {
throw new IllegalStateException(
"No resource name resolver is registered in ResourceName class.");
}
};
/**
* Sets the resource name resolver which is used by the {@link #resolve(Class, String)} method. By
* default, no resolver is registered.
*/
public static void registerResourceNameResolver(Resolver resolver) {
resourceNameResolver = resolver;
}
// ResourceName
// ============
/**
* Creates a new resource name based on given template and path. The path must match the template,
* otherwise null is returned.
*
* @throws ValidationException if the path does not match the template.
*/
public static TemplatedResourceName create(PathTemplate template, String path) {
Map<String, String> values = template.match(path);
if (values == null) {
throw new ValidationException("path '%s' does not match template '%s'", path, template);
}
return new TemplatedResourceName(template, values, null);
}
/**
* Creates a new resource name from a template and a value assignment for variables.
*
* @throws ValidationException if not all variables in the template are bound.
*/
public static TemplatedResourceName create(PathTemplate template, Map<String, String> values) {
if (!values.keySet().containsAll(template.vars())) {
Set<String> unbound = Sets.newLinkedHashSet(template.vars());
unbound.removeAll(values.keySet());
throw new ValidationException("unbound variables: %s", unbound);
}
return new TemplatedResourceName(template, values, null);
}
/**
* Creates a new resource name based on given template and path, where the path contains an
* endpoint. If the path does not match, null is returned.
*/
@Nullable
public static TemplatedResourceName createFromFullName(PathTemplate template, String path) {
Map<String, String> values = template.matchFromFullName(path);
if (values == null) {
return null;
}
return new TemplatedResourceName(template, values, null);
}
private final PathTemplate template;
private final ImmutableMap<String, String> values;
private final String endpoint;
private volatile String stringRepr;
private TemplatedResourceName(
PathTemplate template, Map<String, String> values, String endpoint) {
this.template = template;
this.values = ImmutableMap.copyOf(values);
this.endpoint = endpoint;
}
@Override
public String toString() {
if (stringRepr == null) {
stringRepr = template.instantiate(values);
}
return stringRepr;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TemplatedResourceName)) {
return false;
}
TemplatedResourceName other = (TemplatedResourceName) obj;
return Objects.equals(template, other.template)
&& Objects.equals(endpoint, other.endpoint)
&& Objects.equals(values, other.values);
}
@Override
public int hashCode() {
return Objects.hash(template, endpoint, values);
}
/** Gets the template associated with this resource name. */
public PathTemplate template() {
return template;
}
/** Checks whether the resource name has an endpoint. */
public boolean hasEndpoint() {
return endpoint != null;
}
/** Returns the endpoint of this resource name, or null if none is defined. */
@Nullable
public String endpoint() {
return endpoint;
}
/** Returns a resource name with specified endpoint. */
public TemplatedResourceName withEndpoint(String endpoint) {
return new TemplatedResourceName(template, values, Preconditions.checkNotNull(endpoint));
}
/**
* Returns the parent resource name. For example, if the name is {@code shelves/s1/books/b1}, the
* parent is {@code shelves/s1/books}.
*/
public TemplatedResourceName parentName() {
PathTemplate parentTemplate = template.parentTemplate();
return new TemplatedResourceName(parentTemplate, values, endpoint);
}
/**
* Returns true of the resource name starts with the parent resource name, i.e. is a child of the
* parent.
*/
public boolean startsWith(TemplatedResourceName parentName) {
// TODO: more efficient implementation.
return toString().startsWith(parentName.toString());
}
/**
* Attempts to resolve a resource name into a resource, by calling the associated API. The
* resource name must have an endpoint. An optional version can be specified to determine in which
* version of the API to call.
*/
public <T> T resolve(Class<T> resourceType, @Nullable String version) {
Preconditions.checkArgument(hasEndpoint(), "Resource name must have an endpoint.");
return resourceNameResolver.resolve(resourceType, this, version);
}
// Map Interface
// =============
@Override
public int size() {
return values.size();
}
@Override
public boolean isEmpty() {
return values.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return values.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return values.containsValue(value);
}
@Override
public String get(Object key) {
return values.get(key);
}
@Override
@Deprecated
public String put(String key, String value) {
return values.put(key, value);
}
@Override
@Deprecated
public String remove(Object key) {
return values.remove(key);
}
@Override
@Deprecated
public void putAll(Map<? extends String, ? extends String> m) {
values.putAll(m);
}
@Override
@Deprecated
public void clear() {
values.clear();
}
@Override
public Set<String> keySet() {
return values.keySet();
}
@Override
public Collection<String> values() {
return values.values();
}
@Override
public Set<Entry<String, String>> entrySet() {
return values.entrySet();
}
}