Merge changes from topic 'rem_web_xml'
[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.Optional;
12 import com.google.common.base.Preconditions;
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.concurrent.atomic.AtomicReference;
25 import javax.annotation.Nonnull;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.ext.Provider;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
33 import org.opendaylight.restconf.common.patch.PatchContext;
34 import org.opendaylight.restconf.common.patch.PatchEditOperation;
35 import org.opendaylight.restconf.common.patch.PatchEntity;
36 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
37 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
38 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
40 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
41 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
47 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 @Provider
57 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
58 public class JsonToPatchBodyReader extends AbstractToPatchBodyReader {
59     private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
60
61     public JsonToPatchBodyReader(SchemaContextHandler schemaContextHandler,
62             DOMMountPointServiceHandler mountPointServiceHandler) {
63         super(schemaContextHandler, mountPointServiceHandler);
64     }
65
66     @SuppressWarnings("checkstyle:IllegalCatch")
67     @Override
68     protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
69             throws IOException, WebApplicationException {
70         try {
71             return readFrom(path, entityStream);
72         } catch (final Exception e) {
73             throw propagateExceptionAs(e);
74         }
75     }
76
77     private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
78             throws IOException {
79         final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
80         AtomicReference<String> patchId = new AtomicReference<>();
81         final List<PatchEntity> resultList = read(jsonReader, path, patchId);
82         jsonReader.close();
83
84         return new PatchContext(path, resultList, patchId.get());
85     }
86
87     @SuppressWarnings("checkstyle:IllegalCatch")
88     public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
89             RestconfDocumentedException {
90         try {
91             return readFrom(
92                     ParserIdentifier.toInstanceIdentifier(uriPath, getSchemaContext(),
93                             Optional.fromNullable(getMountPointService())), entityStream);
94         } catch (final Exception e) {
95             propagateExceptionAs(e);
96             return null; // no-op
97         }
98     }
99
100     private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
101         if (exception instanceof RestconfDocumentedException) {
102             throw (RestconfDocumentedException)exception;
103         }
104
105         if (exception instanceof ResultAlreadySetException) {
106             LOG.debug("Error parsing json input:", exception);
107             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
108         }
109
110         throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
111                 ErrorTag.MALFORMED_MESSAGE, exception);
112     }
113
114     private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
115             final AtomicReference<String> patchId) throws IOException {
116         final List<PatchEntity> resultCollection = new ArrayList<>();
117         final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
118                 path.getSchemaContext());
119         final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
120
121         while (in.hasNext()) {
122             switch (in.peek()) {
123                 case STRING:
124                 case NUMBER:
125                     in.nextString();
126                     break;
127                 case BOOLEAN:
128                     Boolean.toString(in.nextBoolean());
129                     break;
130                 case NULL:
131                     in.nextNull();
132                     break;
133                 case BEGIN_ARRAY:
134                     in.beginArray();
135                     break;
136                 case BEGIN_OBJECT:
137                     in.beginObject();
138                     break;
139                 case END_DOCUMENT:
140                     break;
141                 case NAME:
142                     parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
143                     break;
144                 case END_OBJECT:
145                     in.endObject();
146                     break;
147                 case END_ARRAY:
148                     in.endArray();
149                     break;
150
151                 default:
152                     break;
153             }
154         }
155
156         return ImmutableList.copyOf(resultCollection);
157     }
158
159     /**
160      * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
161      *
162      * @param name value of token
163      * @param edit PatchEdit instance
164      * @param in JsonReader reader
165      * @param path InstanceIdentifierContext context
166      * @param codec Draft11StringModuleInstanceIdentifierCodec codec
167      * @param resultCollection collection of parsed edits
168      * @throws IOException if operation fails
169      */
170     private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
171                              @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
172                              @Nonnull final StringModuleInstanceIdentifierCodec codec,
173                              @Nonnull final List<PatchEntity> resultCollection,
174                              @Nonnull final AtomicReference<String> patchId) throws IOException {
175         switch (name) {
176             case "edit":
177                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
178                     in.beginArray();
179
180                     while (in.hasNext()) {
181                         readEditDefinition(edit, in, path, codec);
182                         resultCollection.add(prepareEditOperation(edit));
183                         edit.clear();
184                     }
185
186                     in.endArray();
187                 } else {
188                     readEditDefinition(edit, in, path, codec);
189                     resultCollection.add(prepareEditOperation(edit));
190                     edit.clear();
191                 }
192
193                 break;
194             case "patch-id":
195                 patchId.set(in.nextString());
196                 break;
197             default:
198                 break;
199         }
200     }
201
202     /**
203      * Read one patch edit object from Json input.
204      *
205      * @param edit PatchEdit instance to be filled with read data
206      * @param in JsonReader reader
207      * @param path InstanceIdentifierContext path context
208      * @param codec Draft11StringModuleInstanceIdentifierCodec codec
209      * @throws IOException if operation fails
210      */
211     private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
212                                     @Nonnull final InstanceIdentifierContext<?> path,
213                                     @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
214         String deferredValue = null;
215         in.beginObject();
216
217         while (in.hasNext()) {
218             final String editDefinition = in.nextName();
219             switch (editDefinition) {
220                 case "edit-id":
221                     edit.setId(in.nextString());
222                     break;
223                 case "operation":
224                     edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
225                     break;
226                 case "target":
227                     // target can be specified completely in request URI
228                     final String target = in.nextString();
229                     if (target.equals("/")) {
230                         edit.setTarget(path.getInstanceIdentifier());
231                         edit.setTargetSchemaNode(path.getSchemaContext());
232                     } else {
233                         edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
234                         edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
235                                 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
236                                         .getParent()));
237                     }
238
239                     break;
240                 case "value":
241                     Preconditions.checkArgument(edit.getData() == null && deferredValue == null,
242                             "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(@Nonnull final StringBuilder sb, @Nonnull final 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(@Nonnull final StringBuilder sb, @Nonnull final 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(@Nonnull final JsonReader in,
371             @Nonnull final SchemaNode targetSchemaNode, @Nonnull final 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(@Nonnull final 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(@Nonnull final 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 = Preconditions.checkNotNull(id);
433         }
434
435         PatchEditOperation getOperation() {
436             return operation;
437         }
438
439         void setOperation(final PatchEditOperation operation) {
440             this.operation = Preconditions.checkNotNull(operation);
441         }
442
443         YangInstanceIdentifier getTarget() {
444             return target;
445         }
446
447         void setTarget(final YangInstanceIdentifier target) {
448             this.target = Preconditions.checkNotNull(target);
449         }
450
451         SchemaNode getTargetSchemaNode() {
452             return targetSchemaNode;
453         }
454
455         void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
456             this.targetSchemaNode = Preconditions.checkNotNull(targetSchemaNode);
457         }
458
459         NormalizedNode<?, ?> getData() {
460             return data;
461         }
462
463         void setData(final NormalizedNode<?, ?> data) {
464             this.data = Preconditions.checkNotNull(data);
465         }
466
467         void clear() {
468             id = null;
469             operation = null;
470             target = null;
471             targetSchemaNode = null;
472             data = null;
473         }
474     }
475 }