Eliminate space escaping
[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.text.ParseException;
19 import java.util.HexFormat;
20 import java.util.Objects;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.yangtools.concepts.Immutable;
24 import org.opendaylight.yangtools.yang.common.UnresolvedQName;
25 import org.opendaylight.yangtools.yang.common.UnresolvedQName.Unqualified;
26
27 /**
28  * Intermediate representation of a parsed {@code api-path} string as defined in
29  * <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
30  * as a series of {@link Step}s.
31  */
32 @NonNullByDefault
33 public final class ApiPath implements Immutable {
34     /**
35      * A single step in an {@link ApiPath}.
36      */
37     public abstract static sealed class Step implements Immutable {
38         private final @Nullable String module;
39         private final Unqualified identifier;
40
41         Step(final @Nullable String module, final String identifier) {
42             this.identifier = verifyNotNull(UnresolvedQName.tryLocalName(identifier),
43                 "Unexpected invalid identifier %s", identifier);
44             this.module = module;
45         }
46
47         public Unqualified identifier() {
48             return identifier;
49         }
50
51         public @Nullable String module() {
52             return module;
53         }
54
55         @Override
56         public abstract int hashCode();
57
58         @Override
59         public abstract boolean equals(@Nullable Object obj);
60
61         final boolean equals(final Step other) {
62             return Objects.equals(module, other.module) && identifier.equals(other.identifier);
63         }
64
65         @Override
66         public final String toString() {
67             return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
68         }
69
70         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
71             return helper.add("module", module).add("identifier", identifier);
72         }
73
74         void appendTo(final StringBuilder sb) {
75             if (module != null) {
76                 sb.append(module).append(':');
77             }
78             sb.append(identifier.getLocalName());
79         }
80     }
81
82     /**
83      * An {@code api-identifier} step in a {@link ApiPath}.
84      */
85     public static final class ApiIdentifier extends Step {
86         public ApiIdentifier(final @Nullable String module, final String identifier) {
87             super(module, identifier);
88         }
89
90         @Override
91         public int hashCode() {
92             return Objects.hash(module(), identifier());
93         }
94
95         @Override
96         public boolean equals(final @Nullable Object obj) {
97             return this == obj || obj instanceof ApiIdentifier other && equals(other);
98         }
99     }
100
101     /**
102      * A {@code list-instance} step in a {@link ApiPath}.
103      */
104     public static final class ListInstance extends Step {
105         private final ImmutableList<String> keyValues;
106
107         ListInstance(final @Nullable String module, final String identifier, final ImmutableList<String> keyValues) {
108             super(module, identifier);
109             this.keyValues = requireNonNull(keyValues);
110         }
111
112         public ImmutableList<String> keyValues() {
113             return keyValues;
114         }
115
116         @Override
117         public int hashCode() {
118             return Objects.hash(module(), identifier(), keyValues);
119         }
120
121         @Override
122         public boolean equals(final @Nullable Object obj) {
123             return this == obj || obj instanceof ListInstance other && equals(other)
124                 && keyValues.equals(other.keyValues);
125         }
126
127         @Override
128         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
129             return super.addToStringAttributes(helper).add("keyValues", keyValues);
130         }
131
132         @Override
133         void appendTo(final StringBuilder sb) {
134             super.appendTo(sb);
135             sb.append('=');
136             final var it = keyValues.iterator();
137             while (true) {
138                 sb.append(PERCENT_ESCAPER.escape(it.next()));
139                 if (it.hasNext()) {
140                     sb.append(',');
141                 } else {
142                     break;
143                 }
144             }
145         }
146     }
147
148     // Escaper based on RFC8040-requirement to percent-encode reserved characters, as defined in
149     // https://tools.ietf.org/html/rfc3986#section-2.2
150     public static final Escaper PERCENT_ESCAPER;
151
152     static {
153         final var hexFormat = HexFormat.of().withUpperCase();
154         final var builder = Escapers.builder();
155         for (char ch : new char[] {
156             // Reserved characters as per https://tools.ietf.org/html/rfc3986#section-2.2
157             ':', '/', '?', '#', '[', ']', '@',
158             '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=',
159         }) {
160             builder.addEscape(ch, "%" + hexFormat.toHighHexDigit(ch) + hexFormat.toLowHexDigit(ch));
161         }
162         PERCENT_ESCAPER = builder.build();
163     }
164
165     private static final ApiPath EMPTY = new ApiPath(ImmutableList.of());
166
167     private final ImmutableList<Step> steps;
168
169     private ApiPath(final ImmutableList<Step> steps) {
170         this.steps = requireNonNull(steps);
171     }
172
173     /**
174      * Return an empty ApiPath.
175      *
176      * @return An empty ApiPath.
177      */
178     public static ApiPath empty() {
179         return EMPTY;
180     }
181
182     /**
183      * Parse an {@link ApiPath} from a raw Request URI fragment or another source. The string is expected to contain
184      * percent-encoded bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid
185      * sequences are rejected.
186      *
187      * @param str Request URI part
188      * @return An {@link ApiPath}
189      * @throws NullPointerException if {@code str} is {@code null}
190      * @throws ParseException if the string cannot be parsed
191      */
192     public static ApiPath parse(final String str) throws ParseException {
193         return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newStrict(), str);
194     }
195
196     /**
197      * Parse an {@link ApiPath} from a raw Request URI fragment. The string is expected to contain percent-encoded
198      * bytes. Any sequence of such bytes is interpreted as a {@code UTF-8}-encoded string. Invalid sequences are
199      * rejected, but consecutive slashes may be tolerated, depending on runtime configuration.
200      *
201      * @param str Request URI part
202      * @return An {@link ApiPath}
203      * @throws NullPointerException if {@code str} is {@code null}
204      * @throws ParseException if the string cannot be parsed
205      */
206     public static ApiPath parseUrl(final String str) throws ParseException {
207         return str.isEmpty() ? EMPTY : parseString(ApiPathParser.newUrl(), str);
208     }
209
210     public ImmutableList<Step> steps() {
211         return steps;
212     }
213
214     public int indexOf(final String module, final String identifier) {
215         final var m = requireNonNull(module);
216         final var id = requireNonNull(identifier);
217         for (int i = 0, size = steps.size(); i < size; ++i) {
218             final var step = steps.get(i);
219             if (m.equals(step.module) && id.equals(step.identifier.getLocalName())) {
220                 return i;
221             }
222         }
223         return -1;
224     }
225
226     public ApiPath subPath(final int fromIndex) {
227         return subPath(fromIndex, steps.size());
228     }
229
230     public ApiPath subPath(final int fromIndex, final int toIndex) {
231         final var subList = steps.subList(fromIndex, toIndex);
232         if (subList == steps) {
233             return this;
234         } else if (subList.isEmpty()) {
235             return EMPTY;
236         } else {
237             return new ApiPath(subList);
238         }
239     }
240
241     @Override
242     public int hashCode() {
243         return steps.hashCode();
244     }
245
246     @Override
247     public boolean equals(final @Nullable Object obj) {
248         return obj == this || obj instanceof ApiPath other && steps.equals(other.steps());
249     }
250
251     @Override
252     public String toString() {
253         if (steps.isEmpty()) {
254             return "";
255         }
256         final var sb = new StringBuilder();
257         final var it = steps.iterator();
258         while (true) {
259             it.next().appendTo(sb);
260             if (it.hasNext()) {
261                 sb.append('/');
262             } else {
263                 break;
264             }
265         }
266         return sb.toString();
267     }
268
269     private static ApiPath parseString(final ApiPathParser parser, final String str) throws ParseException {
270         final var steps = parser.parseSteps(str);
271         return steps.isEmpty() ? EMPTY : new ApiPath(steps);
272     }
273 }