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