2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.rest.impl;
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.IOException;
14 import java.io.InputStream;
15 import java.io.InputStreamReader;
16 import java.lang.annotation.Annotation;
17 import java.lang.reflect.Type;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.Optional;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.ext.MessageBodyReader;
27 import javax.ws.rs.ext.Provider;
28 import org.opendaylight.netconf.sal.rest.api.Draft02;
29 import org.opendaylight.netconf.sal.rest.api.RestconfService;
30 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
31 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
32 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.util.RestUtil;
35 import org.opendaylight.yangtools.yang.common.ErrorTag;
36 import org.opendaylight.yangtools.yang.common.ErrorType;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
46 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
49 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
59 Draft02.MediaTypes.DATA + RestconfService.JSON,
60 Draft02.MediaTypes.OPERATION + RestconfService.JSON,
61 MediaType.APPLICATION_JSON
63 public class JsonNormalizedNodeBodyReader
64 extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
66 private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
68 public JsonNormalizedNodeBodyReader(final ControllerContext controllerContext) {
69 super(controllerContext);
73 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
74 final MediaType mediaType) {
78 @SuppressWarnings("checkstyle:IllegalCatch")
80 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
81 final Annotation[] annotations, final MediaType mediaType,
82 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws
83 WebApplicationException {
85 return readFrom(getInstanceIdentifierContext(), entityStream, isPost());
86 } catch (final Exception e) {
87 propagateExceptionAs(e);
92 @SuppressWarnings("checkstyle:IllegalCatch")
93 public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
94 final boolean isPost, final ControllerContext controllerContext) throws RestconfDocumentedException {
97 return readFrom(controllerContext.toInstanceIdentifier(uriPath), entityStream, isPost);
98 } catch (final Exception e) {
99 propagateExceptionAs(e);
100 return null; // no-op
104 private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path,
105 final InputStream entityStream, final boolean isPost)
107 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
108 if (nonEmptyInputStreamOptional.isEmpty()) {
109 return new NormalizedNodeContext(path, null);
111 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
112 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
114 final SchemaInferenceStack parentSchema;
116 // FIXME: We need dispatch for RPC.
117 parentSchema = SchemaInferenceStack.ofSchemaPath(path.getSchemaContext(), path.getSchemaNode().getPath());
118 } else if (path.getSchemaNode() instanceof SchemaContext
119 || SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
120 parentSchema = SchemaInferenceStack.of(path.getSchemaContext());
122 parentSchema = SchemaInferenceStack.ofSchemaPath(path.getSchemaContext(),
123 path.getSchemaNode().getPath().getParent());
126 final JsonParserStream jsonParser = JsonParserStream.create(writer,
127 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()),
128 parentSchema.toInference());
129 final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
130 StandardCharsets.UTF_8));
131 jsonParser.parse(reader);
133 NormalizedNode result = resultHolder.getResult();
134 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
135 InstanceIdentifierContext<? extends SchemaNode> newIIContext;
137 while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
138 final Object childNode = ((DataContainerNode) result).body().iterator().next();
140 iiToDataList.add(result.getIdentifier());
142 result = (NormalizedNode) childNode;
146 if (result instanceof MapEntryNode) {
147 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getIdentifier().getNodeType()));
148 iiToDataList.add(result.getIdentifier());
150 iiToDataList.add(result.getIdentifier());
153 if (result instanceof MapNode) {
154 result = Iterables.getOnlyElement(((MapNode) result).body());
158 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
159 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
161 newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
162 path.getSchemaContext());
164 return new NormalizedNodeContext(newIIContext, result);
167 private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
168 Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
169 LOG.debug("Error parsing json input", exception);
171 if (exception instanceof ResultAlreadySetException) {
172 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
173 + "Are you creating multiple resources/subresources in POST request?", exception);
176 RestconfDocumentedException.throwIfYangError(exception);
177 throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
178 ErrorTag.MALFORMED_MESSAGE, exception);