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.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.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.Optional;
21 import javax.ws.rs.Consumes;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.Provider;
27 import org.opendaylight.netconf.sal.rest.api.Draft02;
28 import org.opendaylight.netconf.sal.rest.api.RestconfService;
29 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
34 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
35 import org.opendaylight.restconf.common.util.RestUtil;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
45 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
58 MediaType.APPLICATION_JSON })
59 public class JsonNormalizedNodeBodyReader
60 extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
62 private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
65 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
66 final MediaType mediaType) {
70 @SuppressWarnings("checkstyle:IllegalCatch")
72 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
73 final Annotation[] annotations, final MediaType mediaType,
74 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
75 WebApplicationException {
77 return readFrom(getInstanceIdentifierContext(), entityStream, isPost());
78 } catch (final Exception e) {
79 propagateExceptionAs(e);
84 @SuppressWarnings("checkstyle:IllegalCatch")
85 public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
86 final boolean isPost) throws RestconfDocumentedException {
89 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream, isPost);
90 } catch (final Exception e) {
91 propagateExceptionAs(e);
96 private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path,
97 final InputStream entityStream, final boolean isPost)
99 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
100 if (!nonEmptyInputStreamOptional.isPresent()) {
101 return new NormalizedNodeContext(path, null);
103 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
104 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
106 final SchemaNode parentSchema;
108 // FIXME: We need dispatch for RPC.
109 parentSchema = path.getSchemaNode();
110 } else if (path.getSchemaNode() instanceof SchemaContext) {
111 parentSchema = path.getSchemaContext();
113 if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
114 parentSchema = path.getSchemaContext();
116 parentSchema = SchemaContextUtil
117 .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
121 final JsonParserStream jsonParser = JsonParserStream.create(writer,
122 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()), parentSchema);
123 final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
124 StandardCharsets.UTF_8));
125 jsonParser.parse(reader);
127 NormalizedNode<?, ?> result = resultHolder.getResult();
128 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
129 InstanceIdentifierContext<? extends SchemaNode> newIIContext;
131 while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
132 final Object childNode = ((DataContainerNode<?>) result).getValue().iterator().next();
134 iiToDataList.add(result.getIdentifier());
136 result = (NormalizedNode<?, ?>) childNode;
140 if (result instanceof MapEntryNode) {
141 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getNodeType()));
142 iiToDataList.add(result.getIdentifier());
144 iiToDataList.add(result.getIdentifier());
147 if (result instanceof MapNode) {
148 result = Iterables.getOnlyElement(((MapNode) result).getValue());
152 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
153 path.getInstanceIdentifier().getPathArguments(), iiToDataList));
155 newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(),
156 path.getSchemaContext());
158 return new NormalizedNodeContext(newIIContext, result);
161 private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
162 if (exception instanceof RestconfDocumentedException) {
163 throw (RestconfDocumentedException)exception;
166 if (exception instanceof ResultAlreadySetException) {
167 LOG.debug("Error parsing json input:", exception);
169 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
170 + "Are you creating multiple resources/subresources in POST request?", exception);
173 LOG.debug("Error parsing json input", exception);
175 throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
176 ErrorTag.MALFORMED_MESSAGE, exception);