Bump upstream versions
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / patch / JsonPatchBodyReader.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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.nb.rfc8040.jersey.providers.patch;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.Throwables;
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.ArrayList;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Optional;
27 import java.util.concurrent.atomic.AtomicReference;
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.WebApplicationException;
30 import javax.ws.rs.ext.Provider;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
33 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.common.patch.PatchContext;
36 import org.opendaylight.restconf.common.patch.PatchEditOperation;
37 import org.opendaylight.restconf.common.patch.PatchEntity;
38 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
40 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
41 import org.opendaylight.yangtools.yang.common.ErrorTag;
42 import org.opendaylight.yangtools.yang.common.ErrorType;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
48 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
49 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
52 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
56 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 @Provider
61 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
62 public class JsonPatchBodyReader extends AbstractPatchBodyReader {
63     private static final Logger LOG = LoggerFactory.getLogger(JsonPatchBodyReader.class);
64
65     public JsonPatchBodyReader(final SchemaContextHandler schemaContextHandler,
66             final DOMMountPointService mountPointService) {
67         super(schemaContextHandler, mountPointService);
68     }
69
70     @SuppressWarnings("checkstyle:IllegalCatch")
71     @Override
72     protected PatchContext readBody(final InstanceIdentifierContext path, final InputStream entityStream)
73             throws WebApplicationException {
74         try {
75             return readFrom(path, entityStream);
76         } catch (final Exception e) {
77             throw propagateExceptionAs(e);
78         }
79     }
80
81     private PatchContext readFrom(final InstanceIdentifierContext path, final InputStream entityStream)
82             throws IOException {
83         final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
84         AtomicReference<String> patchId = new AtomicReference<>();
85         final List<PatchEntity> resultList = read(jsonReader, path, patchId);
86         jsonReader.close();
87
88         return new PatchContext(path, resultList, patchId.get());
89     }
90
91     @SuppressWarnings("checkstyle:IllegalCatch")
92     public PatchContext readFrom(final String uriPath, final InputStream entityStream)
93             throws RestconfDocumentedException {
94         try {
95             return readFrom(
96                     ParserIdentifier.toInstanceIdentifier(uriPath, getSchemaContext(),
97                             Optional.ofNullable(getMountPointService())), entityStream);
98         } catch (final Exception e) {
99             throw propagateExceptionAs(e);
100         }
101     }
102
103     private static RestconfDocumentedException propagateExceptionAs(final Exception exception)
104             throws RestconfDocumentedException {
105         Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
106         LOG.debug("Error parsing json input", exception);
107
108         if (exception instanceof ResultAlreadySetException) {
109             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
110         }
111
112         RestconfDocumentedException.throwIfYangError(exception);
113         throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
114             ErrorTag.MALFORMED_MESSAGE, exception);
115     }
116
117     private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext path,
118             final AtomicReference<String> patchId) throws IOException {
119         final DataSchemaContextTree schemaTree = DataSchemaContextTree.from(path.getSchemaContext());
120         final List<PatchEntity> resultCollection = new ArrayList<>();
121         final JsonPatchBodyReader.PatchEdit edit = new JsonPatchBodyReader.PatchEdit();
122
123         while (in.hasNext()) {
124             switch (in.peek()) {
125                 case STRING:
126                 case NUMBER:
127                     in.nextString();
128                     break;
129                 case BOOLEAN:
130                     Boolean.toString(in.nextBoolean());
131                     break;
132                 case NULL:
133                     in.nextNull();
134                     break;
135                 case BEGIN_ARRAY:
136                     in.beginArray();
137                     break;
138                 case BEGIN_OBJECT:
139                     in.beginObject();
140                     break;
141                 case END_DOCUMENT:
142                     break;
143                 case NAME:
144                     parseByName(in.nextName(), edit, in, path, schemaTree, resultCollection, patchId);
145                     break;
146                 case END_OBJECT:
147                     in.endObject();
148                     break;
149                 case END_ARRAY:
150                     in.endArray();
151                     break;
152
153                 default:
154                     break;
155             }
156         }
157
158         return ImmutableList.copyOf(resultCollection);
159     }
160
161     /**
162      * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
163      *
164      * @param name value of token
165      * @param edit PatchEdit instance
166      * @param in JsonReader reader
167      * @param path InstanceIdentifierContext context
168      * @param codec Draft11StringModuleInstanceIdentifierCodec codec
169      * @param resultCollection collection of parsed edits
170      * @throws IOException if operation fails
171      */
172     private void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
173                              final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext path,
174                              final @NonNull DataSchemaContextTree schemaTree,
175                              final @NonNull List<PatchEntity> resultCollection,
176                              final @NonNull AtomicReference<String> patchId) throws IOException {
177         switch (name) {
178             case "edit":
179                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
180                     in.beginArray();
181
182                     while (in.hasNext()) {
183                         readEditDefinition(edit, in, path, schemaTree);
184                         resultCollection.add(prepareEditOperation(edit));
185                         edit.clear();
186                     }
187
188                     in.endArray();
189                 } else {
190                     readEditDefinition(edit, in, path, schemaTree);
191                     resultCollection.add(prepareEditOperation(edit));
192                     edit.clear();
193                 }
194
195                 break;
196             case "patch-id":
197                 patchId.set(in.nextString());
198                 break;
199             default:
200                 break;
201         }
202     }
203
204     /**
205      * Read one patch edit object from Json input.
206      *
207      * @param edit PatchEdit instance to be filled with read data
208      * @param in JsonReader reader
209      * @param path InstanceIdentifierContext path context
210      * @param codec Draft11StringModuleInstanceIdentifierCodec codec
211      * @throws IOException if operation fails
212      */
213     private void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
214                                     final @NonNull InstanceIdentifierContext path,
215                                     final @NonNull DataSchemaContextTree schemaTree) throws IOException {
216         String deferredValue = null;
217         in.beginObject();
218
219         while (in.hasNext()) {
220             final String editDefinition = in.nextName();
221             switch (editDefinition) {
222                 case "edit-id":
223                     edit.setId(in.nextString());
224                     break;
225                 case "operation":
226                     edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
227                     break;
228                 case "target":
229                     // target can be specified completely in request URI
230                     final String target = in.nextString();
231                     if (target.equals("/")) {
232                         edit.setTarget(path.getInstanceIdentifier());
233                         edit.setTargetSchemaNode(SchemaInferenceStack.of(path.getSchemaContext()).toInference());
234                     } else {
235                         edit.setTarget(ParserIdentifier.parserPatchTarget(path, target));
236
237                         final var stack = schemaTree.enterPath(edit.getTarget()).orElseThrow().stack();
238                         if (!stack.isEmpty()) {
239                             stack.exit();
240                         }
241
242                         if (!stack.isEmpty()) {
243                             final EffectiveStatement<?, ?> parentStmt = stack.currentStatement();
244                             verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
245                         }
246                         edit.setTargetSchemaNode(stack.toInference());
247                     }
248
249                     break;
250                 case "value":
251                     checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
252
253                     if (edit.getTargetSchemaNode() == null) {
254                         // save data defined in value node for next (later) processing, because target needs to be read
255                         // always first and there is no ordering in Json input
256                         deferredValue = readValueNode(in);
257                     } else {
258                         // We have a target schema node, reuse this reader without buffering the value.
259                         edit.setData(readEditData(in, edit.getTargetSchemaNode(), path));
260                     }
261                     break;
262                 default:
263                     // FIXME: this does not look right, as it can wreck our logic
264                     break;
265             }
266         }
267
268         in.endObject();
269
270         if (deferredValue != null) {
271             // read saved data to normalized node when target schema is already known
272             edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
273                 path));
274         }
275     }
276
277     /**
278      * Parse data defined in value node and saves it to buffer.
279      * @param sb Buffer to read value node
280      * @param in JsonReader reader
281      * @throws IOException if operation fails
282      */
283     private String readValueNode(final @NonNull JsonReader in) throws IOException {
284         in.beginObject();
285         final StringBuilder sb = new StringBuilder().append("{\"").append(in.nextName()).append("\":");
286
287         switch (in.peek()) {
288             case BEGIN_ARRAY:
289                 in.beginArray();
290                 sb.append('[');
291
292                 while (in.hasNext()) {
293                     if (in.peek() == JsonToken.STRING) {
294                         sb.append('"').append(in.nextString()).append('"');
295                     } else {
296                         readValueObject(sb, in);
297                     }
298                     if (in.peek() != JsonToken.END_ARRAY) {
299                         sb.append(',');
300                     }
301                 }
302
303                 in.endArray();
304                 sb.append(']');
305                 break;
306             default:
307                 readValueObject(sb, in);
308                 break;
309         }
310
311         in.endObject();
312         return sb.append('}').toString();
313     }
314
315     /**
316      * Parse one value object of data and saves it to buffer.
317      * @param sb Buffer to read value object
318      * @param in JsonReader reader
319      * @throws IOException if operation fails
320      */
321     private void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in) throws IOException {
322         // read simple leaf value
323         if (in.peek() == JsonToken.STRING) {
324             sb.append('"').append(in.nextString()).append('"');
325             return;
326         }
327
328         in.beginObject();
329         sb.append('{');
330
331         while (in.hasNext()) {
332             sb.append('"').append(in.nextName()).append("\":");
333
334             switch (in.peek()) {
335                 case STRING:
336                     sb.append('"').append(in.nextString()).append('"');
337                     break;
338                 case BEGIN_ARRAY:
339                     in.beginArray();
340                     sb.append('[');
341
342                     while (in.hasNext()) {
343                         if (in.peek() == JsonToken.STRING) {
344                             sb.append('"').append(in.nextString()).append('"');
345                         } else {
346                             readValueObject(sb, in);
347                         }
348
349                         if (in.peek() != JsonToken.END_ARRAY) {
350                             sb.append(',');
351                         }
352                     }
353
354                     in.endArray();
355                     sb.append(']');
356                     break;
357                 default:
358                     readValueObject(sb, in);
359             }
360
361             if (in.peek() != JsonToken.END_OBJECT) {
362                 sb.append(',');
363             }
364         }
365
366         in.endObject();
367         sb.append('}');
368     }
369
370     /**
371      * Read patch edit data defined in value node to NormalizedNode.
372      * @param in reader JsonReader reader
373      * @return NormalizedNode representing data
374      */
375     private static NormalizedNode readEditData(final @NonNull JsonReader in,
376              final @NonNull Inference targetSchemaNode, final @NonNull InstanceIdentifierContext path) {
377         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
378         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
379         JsonParserStream.create(writer, JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()),
380             targetSchemaNode).parse(in);
381
382         return resultHolder.getResult();
383     }
384
385     /**
386      * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
387      * @param edit Instance of PatchEdit
388      * @return PatchEntity Patch entity
389      */
390     private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
391         if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
392                 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
393             if (!edit.getOperation().isWithValue()) {
394                 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
395             }
396
397             // for lists allow to manipulate with list items through their parent
398             final YangInstanceIdentifier targetNode;
399             if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
400                 targetNode = edit.getTarget().getParent();
401             } else {
402                 targetNode = edit.getTarget();
403             }
404
405             return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
406         }
407
408         throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
409     }
410
411     /**
412      * Check if data is present when operation requires it and not present when operation data is not allowed.
413      * @param operation Name of operation
414      * @param hasData Data in edit are present/not present
415      * @return true if data is present when operation requires it or if there are no data when operation does not
416      *     allow it, false otherwise
417      */
418     private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
419         return operation.isWithValue() == hasData;
420     }
421
422     /**
423      * Helper class representing one patch edit.
424      */
425     private static final class PatchEdit {
426         private String id;
427         private PatchEditOperation operation;
428         private YangInstanceIdentifier target;
429         private Inference targetSchemaNode;
430         private NormalizedNode data;
431
432         String getId() {
433             return id;
434         }
435
436         void setId(final String id) {
437             this.id = requireNonNull(id);
438         }
439
440         PatchEditOperation getOperation() {
441             return operation;
442         }
443
444         void setOperation(final PatchEditOperation operation) {
445             this.operation = requireNonNull(operation);
446         }
447
448         YangInstanceIdentifier getTarget() {
449             return target;
450         }
451
452         void setTarget(final YangInstanceIdentifier target) {
453             this.target = requireNonNull(target);
454         }
455
456         Inference getTargetSchemaNode() {
457             return targetSchemaNode;
458         }
459
460         void setTargetSchemaNode(final Inference targetSchemaNode) {
461             this.targetSchemaNode = requireNonNull(targetSchemaNode);
462         }
463
464         NormalizedNode getData() {
465             return data;
466         }
467
468         void setData(final NormalizedNode data) {
469             this.data = requireNonNull(data);
470         }
471
472         void clear() {
473             id = null;
474             operation = null;
475             target = null;
476             targetSchemaNode = null;
477             data = null;
478         }
479     }
480 }