Update RESTCONF error mapping
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.nb.rfc8040.jersey.providers;
9
10 import com.google.common.base.Throwables;
11 import com.google.common.collect.Iterables;
12 import com.google.gson.stream.JsonReader;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.nio.charset.StandardCharsets;
16 import java.util.ArrayList;
17 import java.util.List;
18 import javax.ws.rs.Consumes;
19 import javax.ws.rs.WebApplicationException;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.ext.Provider;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
24 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
25 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
28 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
29 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
30 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
31 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.spi.AbstractNormalizedNodeBodyReader;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
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.EffectiveStatementInference;
46 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
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.api.meta.EffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 @Provider
56 @Consumes({ MediaTypes.APPLICATION_YANG_DATA_JSON, MediaType.APPLICATION_JSON })
57 public class JsonNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
58     private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
59
60     public JsonNormalizedNodeBodyReader(final SchemaContextHandler schemaContextHandler,
61             final DOMMountPointService mountPointService) {
62         super(schemaContextHandler, mountPointService);
63     }
64
65     @SuppressWarnings("checkstyle:IllegalCatch")
66     @Override
67     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
68             throws WebApplicationException {
69         try {
70             return readFrom(path, entityStream, isPost());
71         } catch (final Exception e) {
72             propagateExceptionAs(e);
73             return null;
74         }
75     }
76
77     public static NormalizedNodeContext readFrom(
78             final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost) {
79         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
80         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
81
82         final EffectiveStatementInference parentSchema;
83         if (isPost) {
84             parentSchema = SchemaInferenceStack.ofSchemaPath(path.getSchemaContext(),
85                 path.getSchemaNode().getPath()).toInference();
86         } else if (path.getSchemaNode() instanceof SchemaContext
87             || SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
88             parentSchema = SchemaInferenceStack.of(path.getSchemaContext()).toInference();
89         } else {
90             parentSchema = SchemaInferenceStack.ofSchemaPath(path.getSchemaContext(),
91                 path.getSchemaNode().getPath().getParent()).toInference();
92         }
93
94         final JsonParserStream jsonParser = JsonParserStream.create(writer,
95             JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()), parentSchema);
96
97         final JsonReader reader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
98         jsonParser.parse(reader);
99
100         NormalizedNode result = resultHolder.getResult();
101         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
102         InstanceIdentifierContext<? extends SchemaNode> newIIContext;
103
104         while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
105             final Object childNode = ((DataContainerNode) result).body().iterator().next();
106             if (isPost) {
107                 iiToDataList.add(result.getIdentifier());
108             }
109             result = (NormalizedNode) childNode;
110         }
111
112         if (isPost) {
113             if (result instanceof MapEntryNode) {
114                 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getIdentifier().getNodeType()));
115                 iiToDataList.add(result.getIdentifier());
116             } else {
117                 final List<? extends @NonNull EffectiveStatement<?, ?>> parentPath = parentSchema.statementPath();
118                 if (parentPath.isEmpty() || !(parentPath.get(parentPath.size() - 1) instanceof OperationDefinition)) {
119                     iiToDataList.add(result.getIdentifier());
120                 }
121             }
122         } else {
123             if (result instanceof MapNode) {
124                 result = Iterables.getOnlyElement(((MapNode) result).body());
125             }
126         }
127
128         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
129                 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
130
131         newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
132                 path.getSchemaContext());
133
134         return new NormalizedNodeContext(newIIContext, result);
135     }
136
137     private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
138         Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
139         LOG.debug("Error parsing json input", exception);
140
141         if (exception instanceof ResultAlreadySetException) {
142             throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
143                     + "Are you creating multiple resources/subresources in POST request?", exception);
144         }
145
146         RestconfDocumentedException.throwIfYangError(exception);
147         throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
148                 ErrorTag.MALFORMED_MESSAGE, exception);
149     }
150 }