2 * Copyright (c) 2015 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
9 package org.opendaylight.netconf.sal.rest.impl;
11 import com.google.common.collect.ImmutableList;
12 import com.google.gson.stream.JsonReader;
13 import com.google.gson.stream.JsonToken;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.io.StringReader;
18 import java.lang.annotation.Annotation;
19 import java.lang.reflect.Type;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Optional;
25 import java.util.concurrent.atomic.AtomicReference;
26 import javax.annotation.Nonnull;
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.WebApplicationException;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.ext.MessageBodyReader;
32 import javax.ws.rs.ext.Provider;
33 import org.opendaylight.netconf.sal.rest.api.Draft02;
34 import org.opendaylight.netconf.sal.rest.api.RestconfService;
35 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
36 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
37 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
39 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchEditOperation;
42 import org.opendaylight.restconf.common.patch.PatchEntity;
43 import org.opendaylight.restconf.common.util.RestUtil;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
49 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Patch reader for JSON.
61 * @deprecated This class will be replaced by JsonToPatchBodyReader in restconf-nb-rfc8040
65 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
66 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
67 implements MessageBodyReader<PatchContext> {
69 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
71 public JsonToPatchBodyReader(ControllerContext controllerContext) {
72 super(controllerContext);
76 public boolean isReadable(final Class<?> type, final Type genericType,
77 final Annotation[] annotations, final MediaType mediaType) {
81 @SuppressWarnings("checkstyle:IllegalCatch")
83 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
84 final Annotation[] annotations, final MediaType mediaType,
85 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
86 throws WebApplicationException {
88 return readFrom(getInstanceIdentifierContext(), entityStream);
89 } catch (final Exception e) {
90 throw propagateExceptionAs(e);
94 @SuppressWarnings("checkstyle:IllegalCatch")
95 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
96 RestconfDocumentedException {
98 return readFrom(getControllerContext().toInstanceIdentifier(uriPath), entityStream);
99 } catch (final Exception e) {
100 propagateExceptionAs(e);
101 return null; // no-op
105 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
107 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
108 if (!nonEmptyInputStreamOptional.isPresent()) {
109 return new PatchContext(path, null, null);
112 final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
113 StandardCharsets.UTF_8));
114 AtomicReference<String> patchId = new AtomicReference<>();
115 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
118 return new PatchContext(path, resultList, patchId.get());
121 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
122 if (exception instanceof RestconfDocumentedException) {
123 throw (RestconfDocumentedException)exception;
126 if (exception instanceof ResultAlreadySetException) {
127 LOG.debug("Error parsing json input:", exception);
128 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
131 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
132 ErrorTag.MALFORMED_MESSAGE, exception);
135 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
136 final AtomicReference<String> patchId) throws IOException {
137 final List<PatchEntity> resultCollection = new ArrayList<>();
138 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
139 path.getSchemaContext());
140 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
142 while (in.hasNext()) {
149 Boolean.toString(in.nextBoolean());
163 parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
177 return ImmutableList.copyOf(resultCollection);
181 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
183 * @param name value of token
184 * @param edit PatchEdit instance
185 * @param in JsonReader reader
186 * @param path InstanceIdentifierContext context
187 * @param codec StringModuleInstanceIdentifierCodec codec
188 * @param resultCollection collection of parsed edits
189 * @throws IOException if operation fails
191 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
192 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
193 @Nonnull final StringModuleInstanceIdentifierCodec codec,
194 @Nonnull final List<PatchEntity> resultCollection,
195 @Nonnull final AtomicReference<String> patchId) throws IOException {
198 if (in.peek() == JsonToken.BEGIN_ARRAY) {
201 while (in.hasNext()) {
202 readEditDefinition(edit, in, path, codec);
203 resultCollection.add(prepareEditOperation(edit));
209 readEditDefinition(edit, in, path, codec);
210 resultCollection.add(prepareEditOperation(edit));
216 patchId.set(in.nextString());
224 * Read one patch edit object from Json input.
225 * @param edit PatchEdit instance to be filled with read data
226 * @param in JsonReader reader
227 * @param path InstanceIdentifierContext path context
228 * @param codec StringModuleInstanceIdentifierCodec codec
229 * @throws IOException if operation fails
231 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
232 @Nonnull final InstanceIdentifierContext<?> path,
233 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
234 final StringBuffer value = new StringBuffer();
237 while (in.hasNext()) {
238 final String editDefinition = in.nextName();
239 switch (editDefinition) {
241 edit.setId(in.nextString());
244 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
247 // target can be specified completely in request URI
248 final String target = in.nextString();
249 if (target.equals("/")) {
250 edit.setTarget(path.getInstanceIdentifier());
251 edit.setTargetSchemaNode(path.getSchemaContext());
253 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
254 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
255 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
261 // save data defined in value node for next (later) processing, because target needs to be read
262 // always first and there is no ordering in Json input
263 readValueNode(value, in);
272 // read saved data to normalized node when target schema is already known
273 edit.setData(readEditData(new JsonReader(
274 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
278 * Parse data defined in value node and saves it to buffer.
279 * @param value Buffer to read value node
280 * @param in JsonReader reader
281 * @throws IOException if operation fails
283 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
287 value.append("\"" + in.nextName() + "\"" + ":");
289 if (in.peek() == JsonToken.BEGIN_ARRAY) {
293 while (in.hasNext()) {
294 if (in.peek() == JsonToken.STRING) {
295 value.append("\"" + in.nextString() + "\"");
297 readValueObject(value, in);
299 if (in.peek() != JsonToken.END_ARRAY) {
307 readValueObject(value, in);
315 * Parse one value object of data and saves it to buffer.
316 * @param value Buffer to read value object
317 * @param in JsonReader reader
318 * @throws IOException if operation fails
320 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
321 // read simple leaf value
322 if (in.peek() == JsonToken.STRING) {
323 value.append("\"" + in.nextString() + "\"");
330 while (in.hasNext()) {
331 value.append("\"" + in.nextName() + "\"");
334 if (in.peek() == JsonToken.STRING) {
335 value.append("\"" + in.nextString() + "\"");
337 if (in.peek() == JsonToken.BEGIN_ARRAY) {
341 while (in.hasNext()) {
342 if (in.peek() == JsonToken.STRING) {
343 value.append("\"" + in.nextString() + "\"");
345 readValueObject(value, in);
347 if (in.peek() != JsonToken.END_ARRAY) {
355 readValueObject(value, in);
359 if (in.peek() != JsonToken.END_OBJECT) {
369 * Read patch edit data defined in value node to NormalizedNode.
370 * @param in reader JsonReader reader
371 * @return NormalizedNode representing data
373 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
374 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
375 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
376 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
377 JsonParserStream.create(writer,
378 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()),
379 targetSchemaNode).parse(in);
381 return resultHolder.getResult();
385 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
386 * @param edit Instance of PatchEdit
387 * @return PatchEntity Patch entity
389 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
390 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
391 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
392 if (edit.getOperation().isWithValue()) {
393 // for lists allow to manipulate with list items through their parent
394 final YangInstanceIdentifier targetNode;
395 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
396 targetNode = edit.getTarget().getParent();
398 targetNode = edit.getTarget();
401 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
404 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
407 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
411 * Check if data is present when operation requires it and not present when operation data is not allowed.
412 * @param operation Name of operation
413 * @param hasData Data in edit are present/not present
414 * @return true if data is present when operation requires it or if there are no data when operation does not
415 * allow it, false otherwise
417 private static boolean checkDataPresence(@Nonnull final PatchEditOperation operation, final boolean hasData) {
418 return operation.isWithValue() == hasData;
422 * Helper class representing one patch edit.
424 private static final class PatchEdit {
426 private PatchEditOperation operation;
427 private YangInstanceIdentifier target;
428 private SchemaNode targetSchemaNode;
429 private NormalizedNode<?, ?> data;
431 public String getId() {
435 public void setId(final String id) {
439 public PatchEditOperation getOperation() {
440 return this.operation;
443 public void setOperation(final PatchEditOperation operation) {
444 this.operation = operation;
447 public YangInstanceIdentifier getTarget() {
451 public void setTarget(final YangInstanceIdentifier target) {
452 this.target = target;
455 public SchemaNode getTargetSchemaNode() {
456 return this.targetSchemaNode;
459 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
460 this.targetSchemaNode = targetSchemaNode;
463 public NormalizedNode<?, ?> getData() {
467 public void setData(final NormalizedNode<?, ?> data) {
471 public void clear() {
473 this.operation = null;
475 this.targetSchemaNode = null;