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