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