Cleanup RFC8040 media type handling
[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.InputStream;
13 import java.io.InputStreamReader;
14 import java.nio.charset.StandardCharsets;
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.mdsal.dom.api.DOMMountPointService;
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.nb.rfc8040.MediaTypes;
28 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
29 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.spi.AbstractNormalizedNodeBodyReader;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
39 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
43 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Provider
52 @Consumes({ MediaTypes.APPLICATION_YANG_DATA_JSON, MediaType.APPLICATION_JSON })
53 public class JsonNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
54     private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
55
56     public JsonNormalizedNodeBodyReader(final SchemaContextHandler schemaContextHandler,
57             final DOMMountPointService mountPointService) {
58         super(schemaContextHandler, mountPointService);
59     }
60
61     @SuppressWarnings("checkstyle:IllegalCatch")
62     @Override
63     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
64             throws WebApplicationException {
65         try {
66             return readFrom(path, entityStream, isPost());
67         } catch (final Exception e) {
68             propagateExceptionAs(e);
69             return null;
70         }
71     }
72
73     public static NormalizedNodeContext readFrom(
74             final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost) {
75         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
76         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
77
78         final SchemaNode parentSchema;
79         if (isPost) {
80             parentSchema = path.getSchemaNode();
81         } else if (path.getSchemaNode() instanceof SchemaContext
82             || SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
83             parentSchema = path.getSchemaContext();
84         } else {
85             parentSchema = SchemaContextUtil
86                     .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
87         }
88
89         final JsonParserStream jsonParser = JsonParserStream.create(writer,
90             JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()), parentSchema);
91
92         final JsonReader reader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
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                 if (!(parentSchema instanceof OperationDefinition)) {
113                     iiToDataList.add(result.getIdentifier());
114                 }
115             }
116         } else {
117             if (result instanceof MapNode) {
118                 result = Iterables.getOnlyElement(((MapNode) result).getValue());
119             }
120         }
121
122         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
123                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
124
125         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
126                 path.getSchemaContext());
127
128         return new NormalizedNodeContext(newIIContext, result);
129     }
130
131     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
132         if (exception instanceof RestconfDocumentedException) {
133             throw (RestconfDocumentedException)exception;
134         }
135
136         if (exception instanceof ResultAlreadySetException) {
137             LOG.debug("Error parsing json input:", exception);
138
139             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
140                     + "Are you creating multiple resources/subresources in POST request?", exception);
141         }
142
143         LOG.debug("Error parsing json input", exception);
144
145         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
146                 ErrorTag.MALFORMED_MESSAGE, exception);
147     }
148 }