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