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