Bug 8988 - Check for empty payload properly
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / JsonNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.netconf.sal.rest.impl;
9
10 import com.google.common.collect.Iterables;
11 import com.google.gson.stream.JsonReader;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Optional;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.ext.MessageBodyReader;
25 import javax.ws.rs.ext.Provider;
26 import org.opendaylight.netconf.sal.rest.api.Draft02;
27 import org.opendaylight.netconf.sal.rest.api.RestconfService;
28 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
34 import org.opendaylight.restconf.common.util.RestUtil;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
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.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 @Provider
55 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
56         MediaType.APPLICATION_JSON })
57 public class JsonNormalizedNodeBodyReader
58         extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
59
60     private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
61
62     @Override
63     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
64             final MediaType mediaType) {
65         return true;
66     }
67
68     @SuppressWarnings("checkstyle:IllegalCatch")
69     @Override
70     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
71             final Annotation[] annotations, final MediaType mediaType,
72             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
73             WebApplicationException {
74         try {
75             return readFrom(getInstanceIdentifierContext(), entityStream, isPost());
76         } catch (final Exception e) {
77             propagateExceptionAs(e);
78             return null; // no-op
79         }
80     }
81
82     @SuppressWarnings("checkstyle:IllegalCatch")
83     public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
84                                                  final boolean isPost) throws RestconfDocumentedException {
85
86         try {
87             return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream, isPost);
88         } catch (final Exception e) {
89             propagateExceptionAs(e);
90             return null; // no-op
91         }
92     }
93
94     private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path,
95                                                   final InputStream entityStream, final boolean isPost)
96             throws IOException {
97         final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
98         if (!nonEmptyInputStreamOptional.isPresent()) {
99             return new NormalizedNodeContext(path, null);
100         }
101         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
102         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
103
104         final SchemaNode parentSchema;
105         if (isPost) {
106             // FIXME: We need dispatch for RPC.
107             parentSchema = path.getSchemaNode();
108         } else if (path.getSchemaNode() instanceof SchemaContext) {
109             parentSchema = path.getSchemaContext();
110         } else {
111             if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
112                 parentSchema = path.getSchemaContext();
113             } else {
114                 parentSchema = SchemaContextUtil
115                         .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
116             }
117         }
118
119         final JsonParserStream jsonParser = JsonParserStream.create(writer, path.getSchemaContext(), parentSchema);
120         final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get()));
121         jsonParser.parse(reader);
122
123         NormalizedNode<?, ?> result = resultHolder.getResult();
124         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
125         InstanceIdentifierContext<? extends SchemaNode> newIIContext;
126
127         while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
128             final Object childNode = ((DataContainerNode<?>) result).getValue().iterator().next();
129             if (isPost) {
130                 iiToDataList.add(result.getIdentifier());
131             }
132             result = (NormalizedNode<?, ?>) childNode;
133         }
134
135         if (isPost) {
136             if (result instanceof MapEntryNode) {
137                 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getNodeType()));
138                 iiToDataList.add(result.getIdentifier());
139             } else {
140                 iiToDataList.add(result.getIdentifier());
141             }
142         } else {
143             if (result instanceof MapNode) {
144                 result = Iterables.getOnlyElement(((MapNode) result).getValue());
145             }
146         }
147
148         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
149                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
150
151         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
152                 path.getSchemaContext());
153
154         return new NormalizedNodeContext(newIIContext, result);
155     }
156
157     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
158         if (exception instanceof RestconfDocumentedException) {
159             throw (RestconfDocumentedException)exception;
160         }
161
162         if (exception instanceof ResultAlreadySetException) {
163             LOG.debug("Error parsing json input:", exception);
164
165             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
166                     + "Are you creating multiple resources/subresources in POST request?", exception);
167         }
168
169         LOG.debug("Error parsing json input", exception);
170
171         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
172                 ErrorTag.MALFORMED_MESSAGE, exception);
173     }
174 }
175