Split Restconf implementations (draft02 and RFC) - move providers
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / JsonNormalizedNodeBodyReader.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 package org.opendaylight.restconf.nb.rfc8040.jersey.providers;
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.util.ArrayList;
16 import java.util.List;
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.WebApplicationException;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.ext.Provider;
21 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
22 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
25 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
26 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
27 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.spi.AbstractNormalizedNodeBodyReader;
28 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
38 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 @Provider
49 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
50 public class JsonNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
51
52     private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
53
54     @SuppressWarnings("checkstyle:IllegalCatch")
55     @Override
56     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
57             throws IOException, WebApplicationException {
58         try {
59             return readFrom(path, entityStream, isPost());
60         } catch (final Exception e) {
61             propagateExceptionAs(e);
62             return null;
63         }
64     }
65
66     public static NormalizedNodeContext readFrom(
67             final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost)
68             throws IOException {
69         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
70         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
71
72         final SchemaNode parentSchema;
73         if (isPost) {
74             parentSchema = path.getSchemaNode();
75         } else if (path.getSchemaNode() instanceof SchemaContext) {
76             parentSchema = path.getSchemaContext();
77         } else {
78             if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
79                 parentSchema = path.getSchemaContext();
80             } else {
81                 parentSchema = SchemaContextUtil
82                         .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
83             }
84         }
85
86         final JsonParserStream jsonParser = JsonParserStream.create(writer, path.getSchemaContext(), parentSchema);
87         final JsonReader reader = new JsonReader(new InputStreamReader(entityStream));
88         jsonParser.parse(reader);
89
90         NormalizedNode<?, ?> result = resultHolder.getResult();
91         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
92         InstanceIdentifierContext<? extends SchemaNode> newIIContext;
93
94         while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
95             final Object childNode = ((DataContainerNode<?>) result).getValue().iterator().next();
96             if (isPost) {
97                 iiToDataList.add(result.getIdentifier());
98             }
99             result = (NormalizedNode<?, ?>) childNode;
100         }
101
102         if (isPost) {
103             if (result instanceof MapEntryNode) {
104                 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getNodeType()));
105                 iiToDataList.add(result.getIdentifier());
106             } else {
107                 iiToDataList.add(result.getIdentifier());
108             }
109         } else {
110             if (result instanceof MapNode) {
111                 result = Iterables.getOnlyElement(((MapNode) result).getValue());
112             }
113         }
114
115         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
116                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
117
118         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
119                 path.getSchemaContext());
120
121         return new NormalizedNodeContext(newIIContext, result);
122     }
123
124     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
125         if (exception instanceof RestconfDocumentedException) {
126             throw (RestconfDocumentedException)exception;
127         }
128
129         if (exception instanceof ResultAlreadySetException) {
130             LOG.debug("Error parsing json input:", exception);
131
132             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
133                     + "Are you creating multiple resources/subresources in POST request?", exception);
134         }
135
136         LOG.debug("Error parsing json input", exception);
137
138         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
139                 ErrorTag.MALFORMED_MESSAGE, exception);
140     }
141 }