b0f50a6aa046a188903dc183ae57c8af788b1362
[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.Draft17;
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({Draft17.MediaTypes.PATCH + RestconfConstants.JSON})
55 public class JsonToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider
56         implements MessageBodyReader<PATCHContext> {
57
58     private final static 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     @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 static RuntimeException propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
80         if (e instanceof RestconfDocumentedException) {
81             throw (RestconfDocumentedException)e;
82         }
83
84         if (e instanceof ResultAlreadySetException) {
85             LOG.debug("Error parsing json input:", e);
86             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
87         }
88
89         throw new RestconfDocumentedException("Error parsing json input: " + e.getMessage(), ErrorType.PROTOCOL,
90                 ErrorTag.MALFORMED_MESSAGE, e);
91     }
92
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 PATCHContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
104             throws IOException {
105         if (entityStream.available() < 1) {
106             return new PATCHContext(path, null, null);
107         }
108
109         final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
110         final List<PATCHEntity> resultList = read(jsonReader, path);
111         jsonReader.close();
112
113         return new PATCHContext(path, resultList, patchId);
114     }
115
116     private List<PATCHEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
117         final List<PATCHEntity> resultCollection = new ArrayList<>();
118         final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
119                 path.getSchemaContext());
120         final JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();
121
122         while (in.hasNext()) {
123             switch (in.peek()) {
124                 case STRING:
125                 case NUMBER:
126                     in.nextString();
127                     break;
128                 case BOOLEAN:
129                     Boolean.toString(in.nextBoolean());
130                     break;
131                 case NULL:
132                     in.nextNull();
133                     break;
134                 case BEGIN_ARRAY:
135                     in.beginArray();
136                     break;
137                 case BEGIN_OBJECT:
138                     in.beginObject();
139                     break;
140                 case END_DOCUMENT:
141                     break;
142                 case NAME:
143                     parseByName(in.nextName(), edit, in, path, codec, resultCollection);
144                     break;
145                 case END_OBJECT:
146                     in.endObject();
147                     break;
148                 case END_ARRAY:
149                     in.endArray();
150                     break;
151
152                 default:
153                     break;
154             }
155         }
156
157         return ImmutableList.copyOf(resultCollection);
158     }
159
160     /**
161      * Switch value of parsed JsonToken.NAME and read edit definition or patch id
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
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) throws IOException {
174         switch (name) {
175             case "edit" :
176                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
177                     in.beginArray();
178
179                     while (in.hasNext()) {
180                         readEditDefinition(edit, in, path, codec);
181                         resultCollection.add(prepareEditOperation(edit));
182                         edit.clear();
183                     }
184
185                     in.endArray();
186                 } else {
187                     readEditDefinition(edit, in, path, codec);
188                     resultCollection.add(prepareEditOperation(edit));
189                     edit.clear();
190                 }
191
192                 break;
193             case "patch-id" :
194                 this.patchId = in.nextString();
195                 break;
196             default:
197                 break;
198         }
199     }
200
201     /**
202      * Read one patch edit object from Json input
203      * @param edit PatchEdit instance to be filled with read data
204      * @param in JsonReader reader
205      * @param path InstanceIdentifierContext path context
206      * @param codec Draft11StringModuleInstanceIdentifierCodec codec
207      * @throws IOException
208      */
209     private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
210                                     @Nonnull final InstanceIdentifierContext path,
211                                     @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
212         final StringBuffer value = new StringBuffer();
213         in.beginObject();
214
215         while (in.hasNext()) {
216             final String editDefinition = in.nextName();
217             switch (editDefinition) {
218                 case "edit-id" :
219                     edit.setId(in.nextString());
220                     break;
221                 case "operation" :
222                     edit.setOperation(in.nextString());
223                     break;
224                 case "target" :
225                     // target can be specified completely in request URI
226                     final String target = in.nextString();
227                     if (target.equals("/")) {
228                         edit.setTarget(path.getInstanceIdentifier());
229                         edit.setTargetSchemaNode(path.getSchemaContext());
230                     } else {
231                         edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
232                         edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
233                                 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
234                                         .getParent()));
235                     }
236
237                     break;
238                 case "value" :
239                     // save data defined in value node for next (later) processing, because target needs to be read
240                     // always first and there is no ordering in Json input
241                     readValueNode(value, in);
242                     break;
243                 default:
244                     break;
245             }
246         }
247
248         in.endObject();
249
250         // read saved data to normalized node when target schema is already known
251         edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
252     }
253
254     /**
255      * Parse data defined in value node and saves it to buffer
256      * @param value Buffer to read value node
257      * @param in JsonReader reader
258      * @throws IOException
259      */
260     private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
261         in.beginObject();
262         value.append("{");
263
264         value.append("\"" + in.nextName() + "\"" + ":");
265
266         if (in.peek() == JsonToken.BEGIN_ARRAY) {
267             in.beginArray();
268             value.append("[");
269
270             while (in.hasNext()) {
271                 readValueObject(value, in);
272                 if (in.peek() != JsonToken.END_ARRAY) {
273                     value.append(",");
274                 }
275             }
276
277             in.endArray();
278             value.append("]");
279         } else {
280             readValueObject(value, in);
281         }
282
283         in.endObject();
284         value.append("}");
285     }
286
287     /**
288      * Parse one value object of data and saves it to buffer
289      * @param value Buffer to read value object
290      * @param in JsonReader reader
291      * @throws IOException
292      */
293     private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
294         in.beginObject();
295         value.append("{");
296
297         while (in.hasNext()) {
298             value.append("\"" + in.nextName() + "\"");
299             value.append(":");
300
301             if (in.peek() == JsonToken.STRING) {
302                 value.append("\"" + in.nextString() + "\"");
303             } else {
304                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
305                     in.beginArray();
306                     value.append("[");
307
308                     while (in.hasNext()) {
309                         readValueObject(value, in);
310                         if (in.peek() != JsonToken.END_ARRAY) {
311                             value.append(",");
312                         }
313                     }
314
315                     in.endArray();
316                     value.append("]");
317                 } else {
318                     readValueObject(value, in);
319                 }
320             }
321
322             if (in.peek() != JsonToken.END_OBJECT) {
323                 value.append(",");
324             }
325         }
326
327         in.endObject();
328         value.append("}");
329     }
330
331     /**
332      * Read patch edit data defined in value node to NormalizedNode
333      * @param in reader JsonReader reader
334      * @return NormalizedNode representing data
335      */
336     private NormalizedNode readEditData(@Nonnull final JsonReader in, @Nonnull SchemaNode targetSchemaNode,
337                                         @Nonnull InstanceIdentifierContext path) {
338         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
339         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
340         JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
341
342         return resultHolder.getResult();
343     }
344
345     /**
346      * Prepare PATCHEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception
347      * @param edit Instance of PatchEdit
348      * @return PATCHEntity
349      */
350     private PATCHEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
351         if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
352                 && checkDataPresence(edit.getOperation(), (edit.getData() != null))) {
353             if (isPatchOperationWithValue(edit.getOperation())) {
354                 // for lists allow to manipulate with list items through their parent
355                 final YangInstanceIdentifier targetNode;
356                 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
357                     targetNode = edit.getTarget().getParent();
358                 } else {
359                     targetNode = edit.getTarget();
360                 }
361
362                 return new PATCHEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
363             } else {
364                 return new PATCHEntity(edit.getId(), edit.getOperation(), edit.getTarget());
365             }
366         }
367
368         throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
369     }
370
371     /**
372      * Check if data is present when operation requires it and not present when operation data is not allowed
373      * @param operation Name of operation
374      * @param hasData Data in edit are present/not present
375      * @return true if data is present when operation requires it or if there are no data when operation does not
376      * allow it, false otherwise
377      */
378     private boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
379         if (isPatchOperationWithValue(operation)) {
380             if (hasData) {
381                 return true;
382             } else {
383                 return false;
384             }
385         } else  {
386             if (!hasData) {
387                 return true;
388             } else {
389                 return false;
390             }
391         }
392     }
393
394     /**
395      * Helper class representing one patch edit
396      */
397     private static final class PatchEdit {
398         private String id;
399         private String operation;
400         private YangInstanceIdentifier target;
401         private SchemaNode targetSchemaNode;
402         private NormalizedNode data;
403
404         public String getId() {
405             return id;
406         }
407
408         public void setId(String id) {
409             this.id = id;
410         }
411
412         public String getOperation() {
413             return operation;
414         }
415
416         public void setOperation(String operation) {
417             this.operation = operation;
418         }
419
420         public YangInstanceIdentifier getTarget() {
421             return target;
422         }
423
424         public void setTarget(YangInstanceIdentifier target) {
425             this.target = target;
426         }
427
428         public SchemaNode getTargetSchemaNode() {
429             return targetSchemaNode;
430         }
431
432         public void setTargetSchemaNode(SchemaNode targetSchemaNode) {
433             this.targetSchemaNode = targetSchemaNode;
434         }
435
436         public NormalizedNode getData() {
437             return data;
438         }
439
440         public void setData(NormalizedNode data) {
441             this.data = data;
442         }
443
444         public void clear() {
445             id = null;
446             operation = null;
447             target = null;
448             targetSchemaNode = null;
449             data = null;
450         }
451     }
452 }