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