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