Fix various warnings
[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 StringBuffer value = new StringBuffer();
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(value, 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(value.toString())), edit.getTargetSchemaNode(), path));
257     }
258
259     /**
260      * Parse data defined in value node and saves it to buffer.
261      * @param value Buffer to read value node
262      * @param in JsonReader reader
263      * @throws IOException if operation fails
264      */
265     private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
266         in.beginObject();
267         value.append("{");
268
269         value.append("\"" + in.nextName() + "\"" + ":");
270
271         if (in.peek() == JsonToken.BEGIN_ARRAY) {
272             in.beginArray();
273             value.append("[");
274
275             while (in.hasNext()) {
276                 if (in.peek() == JsonToken.STRING) {
277                     value.append("\"" + in.nextString() + "\"");
278                 } else {
279                     readValueObject(value, in);
280                 }
281                 if (in.peek() != JsonToken.END_ARRAY) {
282                     value.append(",");
283                 }
284             }
285
286             in.endArray();
287             value.append("]");
288         } else {
289             readValueObject(value, in);
290         }
291
292         in.endObject();
293         value.append("}");
294     }
295
296     /**
297      * Parse one value object of data and saves it to buffer.
298      * @param value Buffer to read value object
299      * @param in JsonReader reader
300      * @throws IOException if operation fails
301      */
302     private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
303         // read simple leaf value
304         if (in.peek() == JsonToken.STRING) {
305             value.append("\"" + in.nextString() + "\"");
306             return;
307         }
308
309         in.beginObject();
310         value.append("{");
311
312         while (in.hasNext()) {
313             value.append("\"" + in.nextName() + "\"");
314             value.append(":");
315
316             if (in.peek() == JsonToken.STRING) {
317                 value.append("\"" + in.nextString() + "\"");
318             } else {
319                 if (in.peek() == JsonToken.BEGIN_ARRAY) {
320                     in.beginArray();
321                     value.append("[");
322
323                     while (in.hasNext()) {
324                         if (in.peek() == JsonToken.STRING) {
325                             value.append("\"" + in.nextString() + "\"");
326                         } else {
327                             readValueObject(value, in);
328                         }
329                         if (in.peek() != JsonToken.END_ARRAY) {
330                             value.append(",");
331                         }
332                     }
333
334                     in.endArray();
335                     value.append("]");
336                 } else {
337                     readValueObject(value, in);
338                 }
339             }
340
341             if (in.peek() != JsonToken.END_OBJECT) {
342                 value.append(",");
343             }
344         }
345
346         in.endObject();
347         value.append("}");
348     }
349
350     /**
351      * Read patch edit data defined in value node to NormalizedNode.
352      * @param in reader JsonReader reader
353      * @return NormalizedNode representing data
354      */
355     private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
356             @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
357         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
358         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
359         JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
360
361         return resultHolder.getResult();
362     }
363
364     /**
365      * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
366      * @param edit Instance of PatchEdit
367      * @return PatchEntity Patch entity
368      */
369     private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
370         if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
371                 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
372             if (!isPatchOperationWithValue(edit.getOperation())) {
373                 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
374             }
375
376             // for lists allow to manipulate with list items through their parent
377             final YangInstanceIdentifier targetNode;
378             if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
379                 targetNode = edit.getTarget().getParent();
380             } else {
381                 targetNode = edit.getTarget();
382             }
383
384             return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
385         }
386
387         throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
388     }
389
390     /**
391      * Check if data is present when operation requires it and not present when operation data is not allowed.
392      * @param operation Name of operation
393      * @param hasData Data in edit are present/not present
394      * @return true if data is present when operation requires it or if there are no data when operation does not
395      *     allow it, false otherwise
396      */
397     private static boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
398         return isPatchOperationWithValue(operation) == hasData;
399     }
400
401     /**
402      * Helper class representing one patch edit.
403      */
404     private static final class PatchEdit {
405         private String id;
406         private String operation;
407         private YangInstanceIdentifier target;
408         private SchemaNode targetSchemaNode;
409         private NormalizedNode<?, ?> data;
410
411         public String getId() {
412             return id;
413         }
414
415         public void setId(final String id) {
416             this.id = id;
417         }
418
419         public String getOperation() {
420             return operation;
421         }
422
423         public void setOperation(final String operation) {
424             this.operation = operation;
425         }
426
427         public YangInstanceIdentifier getTarget() {
428             return target;
429         }
430
431         public void setTarget(final YangInstanceIdentifier target) {
432             this.target = target;
433         }
434
435         public SchemaNode getTargetSchemaNode() {
436             return targetSchemaNode;
437         }
438
439         public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
440             this.targetSchemaNode = targetSchemaNode;
441         }
442
443         public NormalizedNode<?, ?> getData() {
444             return data;
445         }
446
447         public void setData(final NormalizedNode<?, ?> data) {
448             this.data = data;
449         }
450
451         public void clear() {
452             id = null;
453             operation = null;
454             target = null;
455             targetSchemaNode = null;
456             data = null;
457         }
458     }
459 }