NETCONF-494: use RFC7951 JSON codecs
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / JsonNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2014 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.netconf.sal.rest.impl;
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.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Optional;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.ext.MessageBodyReader;
25 import javax.ws.rs.ext.Provider;
26 import org.opendaylight.netconf.sal.rest.api.Draft02;
27 import org.opendaylight.netconf.sal.rest.api.RestconfService;
28 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
34 import org.opendaylight.restconf.common.util.RestUtil;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
44 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 @Provider
56 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
57         MediaType.APPLICATION_JSON })
58 public class JsonNormalizedNodeBodyReader
59         extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
60
61     private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
62
63     @Override
64     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
65             final MediaType mediaType) {
66         return true;
67     }
68
69     @SuppressWarnings("checkstyle:IllegalCatch")
70     @Override
71     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
72             final Annotation[] annotations, final MediaType mediaType,
73             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
74             WebApplicationException {
75         try {
76             return readFrom(getInstanceIdentifierContext(), entityStream, isPost());
77         } catch (final Exception e) {
78             propagateExceptionAs(e);
79             return null; // no-op
80         }
81     }
82
83     @SuppressWarnings("checkstyle:IllegalCatch")
84     public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
85                                                  final boolean isPost) throws RestconfDocumentedException {
86
87         try {
88             return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream, isPost);
89         } catch (final Exception e) {
90             propagateExceptionAs(e);
91             return null; // no-op
92         }
93     }
94
95     private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path,
96                                                   final InputStream entityStream, final boolean isPost)
97             throws IOException {
98         final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
99         if (!nonEmptyInputStreamOptional.isPresent()) {
100             return new NormalizedNodeContext(path, null);
101         }
102         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
103         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
104
105         final SchemaNode parentSchema;
106         if (isPost) {
107             // FIXME: We need dispatch for RPC.
108             parentSchema = path.getSchemaNode();
109         } else if (path.getSchemaNode() instanceof SchemaContext) {
110             parentSchema = path.getSchemaContext();
111         } else {
112             if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
113                 parentSchema = path.getSchemaContext();
114             } else {
115                 parentSchema = SchemaContextUtil
116                         .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
117             }
118         }
119
120         final JsonParserStream jsonParser = JsonParserStream.create(writer,
121             JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()), parentSchema);
122         final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get()));
123         jsonParser.parse(reader);
124
125         NormalizedNode<?, ?> result = resultHolder.getResult();
126         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
127         InstanceIdentifierContext<? extends SchemaNode> newIIContext;
128
129         while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
130             final Object childNode = ((DataContainerNode<?>) result).getValue().iterator().next();
131             if (isPost) {
132                 iiToDataList.add(result.getIdentifier());
133             }
134             result = (NormalizedNode<?, ?>) childNode;
135         }
136
137         if (isPost) {
138             if (result instanceof MapEntryNode) {
139                 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getNodeType()));
140                 iiToDataList.add(result.getIdentifier());
141             } else {
142                 iiToDataList.add(result.getIdentifier());
143             }
144         } else {
145             if (result instanceof MapNode) {
146                 result = Iterables.getOnlyElement(((MapNode) result).getValue());
147             }
148         }
149
150         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
151                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
152
153         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
154                 path.getSchemaContext());
155
156         return new NormalizedNodeContext(newIIContext, result);
157     }
158
159     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
160         if (exception instanceof RestconfDocumentedException) {
161             throw (RestconfDocumentedException)exception;
162         }
163
164         if (exception instanceof ResultAlreadySetException) {
165             LOG.debug("Error parsing json input:", exception);
166
167             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
168                     + "Are you creating multiple resources/subresources in POST request?", exception);
169         }
170
171         LOG.debug("Error parsing json input", exception);
172
173         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
174                 ErrorTag.MALFORMED_MESSAGE, exception);
175     }
176 }
177