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