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