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