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