Remove "/" sign in AbstractRestconfStreamRegistry
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / api / JsonPatchBody.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2023 PANTHEON.tech, s.r.o.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.restconf.server.api;
10
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableList.Builder;
17 import com.google.gson.stream.JsonReader;
18 import com.google.gson.stream.JsonToken;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.StringReader;
23 import java.nio.charset.StandardCharsets;
24 import java.util.concurrent.atomic.AtomicReference;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.patch.PatchContext;
28 import org.opendaylight.restconf.common.patch.PatchEntity;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
30 import org.opendaylight.yangtools.yang.common.ErrorTag;
31 import org.opendaylight.yangtools.yang.common.ErrorType;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
36 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
37 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
41
42 public final class JsonPatchBody extends PatchBody {
43     public JsonPatchBody(final InputStream inputStream) {
44         super(inputStream);
45     }
46
47     @Override
48     PatchContext toPatchContext(final ResourceContext resource, final InputStream inputStream) throws IOException {
49         try (var jsonReader = new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
50             final var patchId = new AtomicReference<String>();
51             final var resultList = read(jsonReader, resource, patchId);
52             // Note: patchId side-effect of above
53             return new PatchContext(patchId.get(), resultList);
54         }
55     }
56
57     private static ImmutableList<PatchEntity> read(final JsonReader in, final @NonNull ResourceContext resource,
58             final AtomicReference<String> patchId) throws IOException {
59         final var edits = ImmutableList.<PatchEntity>builder();
60         final var edit = new PatchEdit();
61
62         while (in.hasNext()) {
63             switch (in.peek()) {
64                 case STRING:
65                 case NUMBER:
66                     in.nextString();
67                     break;
68                 case BOOLEAN:
69                     Boolean.toString(in.nextBoolean());
70                     break;
71                 case NULL:
72                     in.nextNull();
73                     break;
74                 case BEGIN_ARRAY:
75                     in.beginArray();
76                     break;
77                 case BEGIN_OBJECT:
78                     in.beginObject();
79                     break;
80                 case END_DOCUMENT:
81                     break;
82                 case NAME:
83                     parseByName(in.nextName(), edit, in, resource, edits, patchId);
84                     break;
85                 case END_OBJECT:
86                     in.endObject();
87                     break;
88                 case END_ARRAY:
89                     in.endArray();
90                     break;
91
92                 default:
93                     break;
94             }
95         }
96
97         return edits.build();
98     }
99
100     // Switch value of parsed JsonToken.NAME and read edit definition or patch id
101     private static void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
102             final @NonNull JsonReader in, final @NonNull ResourceContext resource,
103             final @NonNull Builder<PatchEntity> resultCollection, final @NonNull AtomicReference<String> patchId)
104                 throws IOException {
105         switch (name) {
106             case "edit":
107                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
108                     in.beginArray();
109
110                     while (in.hasNext()) {
111                         readEditDefinition(edit, in, resource);
112                         resultCollection.add(prepareEditOperation(edit));
113                         edit.clear();
114                     }
115
116                     in.endArray();
117                 } else {
118                     readEditDefinition(edit, in, resource);
119                     resultCollection.add(prepareEditOperation(edit));
120                     edit.clear();
121                 }
122
123                 break;
124             case "patch-id":
125                 patchId.set(in.nextString());
126                 break;
127             default:
128                 break;
129         }
130     }
131
132     // Read one patch edit object from JSON input
133     private static void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
134             final @NonNull ResourceContext resource) throws IOException {
135         String deferredValue = null;
136         in.beginObject();
137
138         final var codecs = resource.path.databind().jsonCodecs();
139
140         while (in.hasNext()) {
141             final String editDefinition = in.nextName();
142             switch (editDefinition) {
143                 case "edit-id":
144                     edit.setId(in.nextString());
145                     break;
146                 case "operation":
147                     edit.setOperation(Operation.ofName(in.nextString()));
148                     break;
149                 case "target":
150                     // target can be specified completely in request URI
151                     final var target = parsePatchTarget(resource, in.nextString());
152                     edit.setTarget(target.instance());
153                     final var stack = target.inference().toSchemaInferenceStack();
154                     if (!stack.isEmpty()) {
155                         stack.exit();
156                     }
157
158                     if (!stack.isEmpty()) {
159                         final var parentStmt = stack.currentStatement();
160                         verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
161                     }
162                     edit.setTargetSchemaNode(stack.toInference());
163
164                     break;
165                 case "value":
166                     checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
167
168                     if (edit.getTargetSchemaNode() == null) {
169                         // save data defined in value node for next (later) processing, because target needs to be read
170                         // always first and there is no ordering in Json input
171                         deferredValue = readValueNode(in);
172                     } else {
173                         // We have a target schema node, reuse this reader without buffering the value.
174                         edit.setData(readEditData(in, edit.getTargetSchemaNode(), codecs));
175                     }
176                     break;
177                 default:
178                     // FIXME: this does not look right, as it can wreck our logic
179                     break;
180             }
181         }
182
183         in.endObject();
184
185         if (deferredValue != null) {
186             // read saved data to normalized node when target schema is already known
187             edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
188                 codecs));
189         }
190     }
191
192     /**
193      * Parse data defined in value node and saves it to buffer.
194      * @param sb Buffer to read value node
195      * @param in JsonReader reader
196      * @throws IOException if operation fails
197      */
198     private static String readValueNode(final @NonNull JsonReader in) throws IOException {
199         in.beginObject();
200         final StringBuilder sb = new StringBuilder().append("{\"").append(in.nextName()).append("\":");
201
202         switch (in.peek()) {
203             case BEGIN_ARRAY:
204                 in.beginArray();
205                 sb.append('[');
206
207                 while (in.hasNext()) {
208                     if (in.peek() == JsonToken.STRING) {
209                         sb.append('"').append(in.nextString()).append('"');
210                     } else {
211                         readValueObject(sb, in);
212                     }
213                     if (in.peek() != JsonToken.END_ARRAY) {
214                         sb.append(',');
215                     }
216                 }
217
218                 in.endArray();
219                 sb.append(']');
220                 break;
221             default:
222                 readValueObject(sb, in);
223                 break;
224         }
225
226         in.endObject();
227         return sb.append('}').toString();
228     }
229
230     /**
231      * Parse one value object of data and saves it to buffer.
232      * @param sb Buffer to read value object
233      * @param in JsonReader reader
234      * @throws IOException if operation fails
235      */
236     private static void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in)
237         throws IOException {
238         // read simple leaf value
239         if (in.peek() == JsonToken.STRING) {
240             sb.append('"').append(in.nextString()).append('"');
241             return;
242         }
243
244         in.beginObject();
245         sb.append('{');
246
247         while (in.hasNext()) {
248             sb.append('"').append(in.nextName()).append("\":");
249
250             switch (in.peek()) {
251                 case STRING:
252                     sb.append('"').append(in.nextString()).append('"');
253                     break;
254                 case BEGIN_ARRAY:
255                     in.beginArray();
256                     sb.append('[');
257
258                     while (in.hasNext()) {
259                         if (in.peek() == JsonToken.STRING) {
260                             sb.append('"').append(in.nextString()).append('"');
261                         } else {
262                             readValueObject(sb, in);
263                         }
264
265                         if (in.peek() != JsonToken.END_ARRAY) {
266                             sb.append(',');
267                         }
268                     }
269
270                     in.endArray();
271                     sb.append(']');
272                     break;
273                 default:
274                     readValueObject(sb, in);
275             }
276
277             if (in.peek() != JsonToken.END_OBJECT) {
278                 sb.append(',');
279             }
280         }
281
282         in.endObject();
283         sb.append('}');
284     }
285
286     /**
287      * Read patch edit data defined in value node to NormalizedNode.
288      * @param in reader JsonReader reader
289      * @return NormalizedNode representing data
290      */
291     private static NormalizedNode readEditData(final @NonNull JsonReader in, final @NonNull Inference targetSchemaNode,
292             final @NonNull JSONCodecFactory codecs) {
293         final var resultHolder = new NormalizationResultHolder();
294         final var writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
295         JsonParserStream.create(writer, codecs, targetSchemaNode).parse(in);
296         return resultHolder.getResult().data();
297     }
298
299     /**
300      * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
301      * @param edit Instance of PatchEdit
302      * @return PatchEntity Patch entity
303      */
304     private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
305         if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
306             && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
307             if (!requiresValue(edit.getOperation())) {
308                 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
309             }
310
311             // for lists allow to manipulate with list items through their parent
312             final YangInstanceIdentifier targetNode;
313             if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
314                 targetNode = edit.getTarget().getParent();
315             } else {
316                 targetNode = edit.getTarget();
317             }
318
319             return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
320         }
321
322         throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
323     }
324
325     /**
326      * Check if data is present when operation requires it and not present when operation data is not allowed.
327      * @param operation Name of operation
328      * @param hasData Data in edit are present/not present
329      * @return true if data is present when operation requires it or if there are no data when operation does not
330      *     allow it, false otherwise
331      */
332     private static boolean checkDataPresence(final @NonNull Operation operation, final boolean hasData) {
333         return requiresValue(operation)  == hasData;
334     }
335
336     /**
337      * Helper class representing one patch edit.
338      */
339     private static final class PatchEdit {
340         private String id;
341         private Operation operation;
342         private YangInstanceIdentifier target;
343         private Inference targetSchemaNode;
344         private NormalizedNode data;
345
346         String getId() {
347             return id;
348         }
349
350         void setId(final String id) {
351             this.id = requireNonNull(id);
352         }
353
354         Operation getOperation() {
355             return operation;
356         }
357
358         void setOperation(final Operation operation) {
359             this.operation = requireNonNull(operation);
360         }
361
362         YangInstanceIdentifier getTarget() {
363             return target;
364         }
365
366         void setTarget(final YangInstanceIdentifier target) {
367             this.target = requireNonNull(target);
368         }
369
370         Inference getTargetSchemaNode() {
371             return targetSchemaNode;
372         }
373
374         void setTargetSchemaNode(final Inference targetSchemaNode) {
375             this.targetSchemaNode = requireNonNull(targetSchemaNode);
376         }
377
378         NormalizedNode getData() {
379             return data;
380         }
381
382         void setData(final NormalizedNode data) {
383             this.data = requireNonNull(data);
384         }
385
386         void clear() {
387             id = null;
388             operation = null;
389             target = null;
390             targetSchemaNode = null;
391             data = null;
392         }
393     }
394 }