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