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