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