2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.api;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
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;
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.
40 public record ApiPath(ImmutableList<Step> steps) implements HierarchicalIdentifier<ApiPath> {
42 private static final long serialVersionUID = 1L;
45 * A single step in an {@link ApiPath}.
47 public abstract static sealed class Step implements Immutable {
48 private final @Nullable String module;
49 private final Unqualified identifier;
51 Step(final @Nullable String module, final String identifier) {
52 this.identifier = verifyNotNull(UnresolvedQName.tryLocalName(identifier),
53 "Unexpected invalid identifier %s", identifier);
57 public Unqualified identifier() {
61 public @Nullable String module() {
66 public abstract int hashCode();
69 public abstract boolean equals(@Nullable Object obj);
71 final boolean equals(final Step other) {
72 return Objects.equals(module, other.module) && identifier.equals(other.identifier);
76 public final String toString() {
77 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
80 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
81 return helper.add("module", module).add("identifier", identifier);
84 void appendTo(final StringBuilder sb) {
86 sb.append(module).append(':');
88 sb.append(identifier.getLocalName());
93 * An {@code api-identifier} step in a {@link ApiPath}.
95 public static final class ApiIdentifier extends Step {
96 public ApiIdentifier(final @Nullable String module, final String identifier) {
97 super(module, identifier);
101 public int hashCode() {
102 return Objects.hash(module(), identifier());
106 public boolean equals(final @Nullable Object obj) {
107 return this == obj || obj instanceof ApiIdentifier other && equals(other);
112 * A {@code list-instance} step in a {@link ApiPath}.
114 public static final class ListInstance extends Step {
115 private final ImmutableList<String> keyValues;
117 public ListInstance(final @Nullable String module, final String identifier,
118 final ImmutableList<String> keyValues) {
119 super(module, identifier);
120 this.keyValues = requireNonNull(keyValues);
123 public ImmutableList<String> keyValues() {
128 public int hashCode() {
129 return Objects.hash(module(), identifier(), keyValues);
133 public boolean equals(final @Nullable Object obj) {
134 return this == obj || obj instanceof ListInstance other && equals(other)
135 && keyValues.equals(other.keyValues);
139 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
140 return super.addToStringAttributes(helper).add("keyValues", keyValues);
144 void appendTo(final StringBuilder sb) {
147 final var it = keyValues.iterator();
149 sb.append(PERCENT_ESCAPER.escape(it.next()));
159 // Escaper based on RFC8040-requirement to percent-encode reserved characters, as defined in
160 // https://tools.ietf.org/html/rfc3986#section-2.2
161 public static final Escaper PERCENT_ESCAPER;
164 final var hexFormat = HexFormat.of().withUpperCase();
165 final var builder = Escapers.builder();
166 for (char ch : new char[] {
167 // Reserved characters as per https://tools.ietf.org/html/rfc3986#section-2.2
168 ':', '/', '?', '#', '[', ']', '@',
169 '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=',
171 builder.addEscape(ch, "%" + hexFormat.toHighHexDigit(ch) + hexFormat.toLowHexDigit(ch));
173 PERCENT_ESCAPER = builder.build();
176 private static final ApiPath EMPTY = new ApiPath(ImmutableList.of());
179 requireNonNull(steps);
183 * Return an empty ApiPath.
185 * @return An empty ApiPath.
187 public static ApiPath empty() {
191 public static ApiPath of(final List<Step> steps) {
192 return steps.isEmpty() ? EMPTY : new ApiPath(ImmutableList.copyOf(steps));
196 * Parse an {@link ApiPath} from a raw Request URI fragment or another source. The string is expected to contain
197 * percent-encoded bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid
198 * sequences are rejected.
200 * @param str Request URI part
201 * @return An {@link ApiPath}
202 * @throws NullPointerException if {@code str} is {@code null}
203 * @throws ParseException if the string cannot be parsed
205 public static ApiPath parse(final String str) throws ParseException {
206 return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newStrict(), str);
210 * Parse an {@link ApiPath} from a raw Request URI fragment. The string is expected to contain percent-encoded
211 * bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid sequences are
212 * rejected, but consecutive slashes may be tolerated, depending on runtime configuration.
214 * @param str Request URI part
215 * @return An {@link ApiPath}
216 * @throws NullPointerException if {@code str} is {@code null}
217 * @throws ParseException if the string cannot be parsed
219 public static ApiPath parseUrl(final String str) throws ParseException {
220 return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newUrl(), str);
224 * Return the {@link Step}s of this path.
228 public ImmutableList<Step> steps() {
233 public boolean contains(final ApiPath other) {
237 final var oit = other.steps.iterator();
238 for (var step : steps) {
239 if (!oit.hasNext() || !step.equals(oit.next())) {
247 * Returns the index of a Step in this path matching specified module and identifier. This method is equivalent to
248 * {@code indexOf(module, identifier, 0)}.
250 * @param module Requested {@link Step#module()}
251 * @param identifier Requested {@link Step#identifier()}
252 * @return Index of the step in {@link #steps}, or {@code -1} if a matching step is not found
253 * @throws NullPointerException if {@code identifier} is {@code null}
255 public int indexOf(final String module, final String identifier) {
256 return indexOf(module, identifier, 0);
260 * Returns the index of a Step in this path matching specified module and identifier, starting search at specified
263 * @param module Requested {@link Step#module()}
264 * @param identifier Requested {@link Step#identifier()}
265 * @param fromIndex index from which to search
266 * @return Index of the step in {@link #steps}, or {@code -1} if a matching step is not found
267 * @throws NullPointerException if {@code identifier} is {@code null}
269 public int indexOf(final String module, final String identifier, final int fromIndex) {
270 final var id = requireNonNull(identifier);
271 for (int i = fromIndex, size = steps.size(); i < size; ++i) {
272 final var step = steps.get(i);
273 if (id.equals(step.identifier.getLocalName()) && Objects.equals(module, step.module)) {
280 public ApiPath subPath(final int fromIndex) {
281 return subPath(fromIndex, steps.size());
284 public ApiPath subPath(final int fromIndex, final int toIndex) {
285 final var subList = steps.subList(fromIndex, toIndex);
286 return subList == steps ? this : of(subList);
290 public int hashCode() {
291 return steps.hashCode();
295 public boolean equals(final @Nullable Object obj) {
296 return obj == this || obj instanceof ApiPath other && steps.equals(other.steps());
300 public String toString() {
301 if (steps.isEmpty()) {
304 final var sb = new StringBuilder();
305 final var it = steps.iterator();
307 it.next().appendTo(sb);
314 return sb.toString();
318 Object writeReplace() throws ObjectStreamException {
319 return new APv1(toString());
323 private void writeObject(final ObjectOutputStream stream) throws IOException {
328 private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
333 private void readObjectNoData() throws ObjectStreamException {
337 private NotSerializableException nse() {
338 return new NotSerializableException(getClass().getName());
341 private static ApiPath parseString(final ApiPathParser parser, final String str) throws ParseException {
342 return of(parser.parseSteps(str));