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