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