Turn ApiPath into a record
[netconf.git] / protocol / restconf-api / src / main / java / org / opendaylight / restconf / api / ApiPath.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.api;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.escape.Escaper;
17 import com.google.common.escape.Escapers;
18 import java.io.IOException;
19 import java.io.NotSerializableException;
20 import java.io.ObjectInputStream;
21 import java.io.ObjectOutputStream;
22 import java.io.ObjectStreamException;
23 import java.text.ParseException;
24 import java.util.HexFormat;
25 import java.util.List;
26 import java.util.Objects;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.yangtools.concepts.HierarchicalIdentifier;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.yang.common.UnresolvedQName;
32 import org.opendaylight.yangtools.yang.common.UnresolvedQName.Unqualified;
33
34 /**
35  * Intermediate representation of a parsed {@code api-path} string as defined in
36  * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-3.5.3.1">RFC section 3.5.3.1</a>. It models the path
37  * as a series of {@link Step}s.
38  */
39 @NonNullByDefault
40 public record ApiPath(ImmutableList<Step> steps) implements HierarchicalIdentifier<ApiPath> {
41     @java.io.Serial
42     private static final long serialVersionUID = 1L;
43
44     /**
45      * A single step in an {@link ApiPath}.
46      */
47     public abstract static sealed class Step implements Immutable {
48         private final @Nullable String module;
49         private final Unqualified identifier;
50
51         Step(final @Nullable String module, final String identifier) {
52             this.identifier = verifyNotNull(UnresolvedQName.tryLocalName(identifier),
53                 "Unexpected invalid identifier %s", identifier);
54             this.module = module;
55         }
56
57         public Unqualified identifier() {
58             return identifier;
59         }
60
61         public @Nullable String module() {
62             return module;
63         }
64
65         @Override
66         public abstract int hashCode();
67
68         @Override
69         public abstract boolean equals(@Nullable Object obj);
70
71         final boolean equals(final Step other) {
72             return Objects.equals(module, other.module) && identifier.equals(other.identifier);
73         }
74
75         @Override
76         public final String toString() {
77             return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
78         }
79
80         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
81             return helper.add("module", module).add("identifier", identifier);
82         }
83
84         void appendTo(final StringBuilder sb) {
85             if (module != null) {
86                 sb.append(module).append(':');
87             }
88             sb.append(identifier.getLocalName());
89         }
90     }
91
92     /**
93      * An {@code api-identifier} step in a {@link ApiPath}.
94      */
95     public static final class ApiIdentifier extends Step {
96         public ApiIdentifier(final @Nullable String module, final String identifier) {
97             super(module, identifier);
98         }
99
100         @Override
101         public int hashCode() {
102             return Objects.hash(module(), identifier());
103         }
104
105         @Override
106         public boolean equals(final @Nullable Object obj) {
107             return this == obj || obj instanceof ApiIdentifier other && equals(other);
108         }
109     }
110
111     /**
112      * A {@code list-instance} step in a {@link ApiPath}.
113      */
114     public static final class ListInstance extends Step {
115         private final ImmutableList<String> keyValues;
116
117         ListInstance(final @Nullable String module, final String identifier, final ImmutableList<String> keyValues) {
118             super(module, identifier);
119             this.keyValues = requireNonNull(keyValues);
120         }
121
122         public ImmutableList<String> keyValues() {
123             return keyValues;
124         }
125
126         @Override
127         public int hashCode() {
128             return Objects.hash(module(), identifier(), keyValues);
129         }
130
131         @Override
132         public boolean equals(final @Nullable Object obj) {
133             return this == obj || obj instanceof ListInstance other && equals(other)
134                 && keyValues.equals(other.keyValues);
135         }
136
137         @Override
138         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
139             return super.addToStringAttributes(helper).add("keyValues", keyValues);
140         }
141
142         @Override
143         void appendTo(final StringBuilder sb) {
144             super.appendTo(sb);
145             sb.append('=');
146             final var it = keyValues.iterator();
147             while (true) {
148                 sb.append(PERCENT_ESCAPER.escape(it.next()));
149                 if (it.hasNext()) {
150                     sb.append(',');
151                 } else {
152                     break;
153                 }
154             }
155         }
156     }
157
158     // Escaper based on RFC8040-requirement to percent-encode reserved characters, as defined in
159     // https://tools.ietf.org/html/rfc3986#section-2.2
160     public static final Escaper PERCENT_ESCAPER;
161
162     static {
163         final var hexFormat = HexFormat.of().withUpperCase();
164         final var builder = Escapers.builder();
165         for (char ch : new char[] {
166             // Reserved characters as per https://tools.ietf.org/html/rfc3986#section-2.2
167             ':', '/', '?', '#', '[', ']', '@',
168             '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=',
169         }) {
170             builder.addEscape(ch, "%" + hexFormat.toHighHexDigit(ch) + hexFormat.toLowHexDigit(ch));
171         }
172         PERCENT_ESCAPER = builder.build();
173     }
174
175     private static final ApiPath EMPTY = new ApiPath(ImmutableList.of());
176
177     public ApiPath {
178         requireNonNull(steps);
179     }
180
181     /**
182      * Return an empty ApiPath.
183      *
184      * @return An empty ApiPath.
185      */
186     public static ApiPath empty() {
187         return EMPTY;
188     }
189
190     public static ApiPath of(final List<Step> steps) {
191         return steps.isEmpty() ? EMPTY : new ApiPath(ImmutableList.copyOf(steps));
192     }
193
194     /**
195      * Parse an {@link ApiPath} from a raw Request URI fragment or another source. The string is expected to contain
196      * percent-encoded bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid
197      * sequences are rejected.
198      *
199      * @param str Request URI part
200      * @return An {@link ApiPath}
201      * @throws NullPointerException if {@code str} is {@code null}
202      * @throws ParseException if the string cannot be parsed
203      */
204     public static ApiPath parse(final String str) throws ParseException {
205         return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newStrict(), str);
206     }
207
208     /**
209      * Parse an {@link ApiPath} from a raw Request URI fragment. The string is expected to contain percent-encoded
210      * bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid sequences are
211      * rejected, but consecutive slashes may be tolerated, depending on runtime configuration.
212      *
213      * @param str Request URI part
214      * @return An {@link ApiPath}
215      * @throws NullPointerException if {@code str} is {@code null}
216      * @throws ParseException if the string cannot be parsed
217      */
218     public static ApiPath parseUrl(final String str) throws ParseException {
219         return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newUrl(), str);
220     }
221
222     /**
223      * Return the {@link Step}s of this path.
224      *
225      * @return Path steps
226      */
227     public ImmutableList<Step> steps() {
228         return steps;
229     }
230
231     @Override
232     public boolean contains(final ApiPath other) {
233         if (this == other) {
234             return true;
235         }
236         final var oit = other.steps.iterator();
237         for (var step : steps) {
238             if (!oit.hasNext() || !step.equals(oit.next())) {
239                 return false;
240             }
241         }
242         return true;
243     }
244
245     /**
246      * Returns the index of a Step in this path matching specified module and identifier. This method is equivalent to
247      * {@code indexOf(module, identifier, 0)}.
248      *
249      * @param module Requested {@link Step#module()}
250      * @param identifier Requested {@link Step#identifier()}
251      * @return Index of the step in {@link #steps}, or {@code -1} if a matching step is not found
252      * @throws NullPointerException if {@code identifier} is {@code null}
253      */
254     public int indexOf(final String module, final String identifier) {
255         return indexOf(module, identifier, 0);
256     }
257
258     /**
259      * Returns the index of a Step in this path matching specified module and identifier, starting search at specified
260      * index.
261      *
262      * @param module Requested {@link Step#module()}
263      * @param identifier Requested {@link Step#identifier()}
264      * @param fromIndex index from which to search
265      * @return Index of the step in {@link #steps}, or {@code -1} if a matching step is not found
266      * @throws NullPointerException if {@code identifier} is {@code null}
267      */
268     public int indexOf(final String module, final String identifier, final int fromIndex) {
269         final var id = requireNonNull(identifier);
270         for (int i = fromIndex, size = steps.size(); i < size; ++i) {
271             final var step = steps.get(i);
272             if (id.equals(step.identifier.getLocalName()) && Objects.equals(module, step.module)) {
273                 return i;
274             }
275         }
276         return -1;
277     }
278
279     public ApiPath subPath(final int fromIndex) {
280         return subPath(fromIndex, steps.size());
281     }
282
283     public ApiPath subPath(final int fromIndex, final int toIndex) {
284         final var subList = steps.subList(fromIndex, toIndex);
285         return subList == steps ? this : of(subList);
286     }
287
288     @Override
289     public int hashCode() {
290         return steps.hashCode();
291     }
292
293     @Override
294     public boolean equals(final @Nullable Object obj) {
295         return obj == this || obj instanceof ApiPath other && steps.equals(other.steps());
296     }
297
298     @Override
299     public String toString() {
300         if (steps.isEmpty()) {
301             return "";
302         }
303         final var sb = new StringBuilder();
304         final var it = steps.iterator();
305         while (true) {
306             it.next().appendTo(sb);
307             if (it.hasNext()) {
308                 sb.append('/');
309             } else {
310                 break;
311             }
312         }
313         return sb.toString();
314     }
315
316     @java.io.Serial
317     Object writeReplace() throws ObjectStreamException {
318         return new APv1(toString());
319     }
320
321     @java.io.Serial
322     private void writeObject(final ObjectOutputStream stream) throws IOException {
323         throw nse();
324     }
325
326     @java.io.Serial
327     private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
328         throw nse();
329     }
330
331     @java.io.Serial
332     private void readObjectNoData() throws ObjectStreamException {
333         throw nse();
334     }
335
336     private NotSerializableException nse() {
337         return new NotSerializableException(getClass().getName());
338     }
339
340     private static ApiPath parseString(final ApiPathParser parser, final String str) throws ParseException {
341         return of(parser.parseSteps(str));
342     }
343 }