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