Fix various warnings
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / jersey / providers / JsonNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2016 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.restconf.jersey.providers;
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.core.Request;
24 import javax.ws.rs.core.UriInfo;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.Provider;
27 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
28 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
29 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
30 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
31 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
32 import org.opendaylight.restconf.Rfc8040;
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({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
55 public class JsonNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
56         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;
77         }
78     }
79
80     private static NormalizedNodeContext readFrom(
81             final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost)
82             throws IOException {
83         if (entityStream.available() < 1) {
84             return new NormalizedNodeContext(path, null);
85         }
86         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
87         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
88
89         final SchemaNode parentSchema;
90         if (isPost) {
91             parentSchema = path.getSchemaNode();
92         } else if (path.getSchemaNode() instanceof SchemaContext) {
93             parentSchema = path.getSchemaContext();
94         } else {
95             if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
96                 parentSchema = path.getSchemaContext();
97             } else {
98                 parentSchema = SchemaContextUtil
99                         .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
100             }
101         }
102
103         final JsonParserStream jsonParser = JsonParserStream.create(writer, path.getSchemaContext(), parentSchema);
104         final JsonReader reader = new JsonReader(new InputStreamReader(entityStream));
105         jsonParser.parse(reader);
106
107         NormalizedNode<?, ?> result = resultHolder.getResult();
108         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
109         InstanceIdentifierContext<? extends SchemaNode> newIIContext;
110
111         while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
112             final Object childNode = ((DataContainerNode<?>) result).getValue().iterator().next();
113             if (isPost) {
114                 iiToDataList.add(result.getIdentifier());
115             }
116             result = (NormalizedNode<?, ?>) childNode;
117         }
118
119         if (isPost) {
120             if (result instanceof MapEntryNode) {
121                 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getNodeType()));
122                 iiToDataList.add(result.getIdentifier());
123             } else {
124                 iiToDataList.add(result.getIdentifier());
125             }
126         } else {
127             if (result instanceof MapNode) {
128                 result = Iterables.getOnlyElement(((MapNode) result).getValue());
129             }
130         }
131
132         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
133                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
134
135         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
136                 path.getSchemaContext());
137
138         return new NormalizedNodeContext(newIIContext, result);
139     }
140
141     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
142         if (exception instanceof RestconfDocumentedException) {
143             throw (RestconfDocumentedException)exception;
144         }
145
146         if (exception instanceof ResultAlreadySetException) {
147             LOG.debug("Error parsing json input:", exception);
148
149             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
150                     + "Are you creating multiple resources/subresources in POST request?");
151         }
152
153         LOG.debug("Error parsing json input", exception);
154
155         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
156                 ErrorTag.MALFORMED_MESSAGE, exception);
157     }
158
159     public void injectParams(final UriInfo uriInfo, final Request request) {
160         setUriInfo(uriInfo);
161         setRequest(request);
162     }
163 }
164