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