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