2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2023 PANTHEON.tech, s.r.o.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.restconf.nb.rfc8040.databind;
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.collect.ImmutableList;
16 import com.google.gson.stream.JsonReader;
17 import com.google.gson.stream.JsonToken;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.io.StringReader;
22 import java.nio.charset.StandardCharsets;
23 import java.util.concurrent.atomic.AtomicReference;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.patch.PatchContext;
28 import org.opendaylight.restconf.common.patch.PatchEntity;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
30 import org.opendaylight.yangtools.yang.common.ErrorTag;
31 import org.opendaylight.yangtools.yang.common.ErrorType;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
36 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
37 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
39 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
44 public final class JsonPatchBody extends PatchBody {
45 public JsonPatchBody(final InputStream inputStream) {
50 PatchContext toPatchContext(final InstanceIdentifierContext targetResource, final InputStream inputStream)
52 try (var jsonReader = new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
53 final var patchId = new AtomicReference<String>();
54 final var resultList = read(jsonReader, targetResource, patchId);
55 return new PatchContext(targetResource, resultList, patchId.get());
59 private static ImmutableList<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext path,
60 final AtomicReference<String> patchId) throws IOException {
61 final var schemaTree = DataSchemaContextTree.from(path.getSchemaContext());
62 final var edits = ImmutableList.<PatchEntity>builder();
63 final var edit = new PatchEdit();
65 while (in.hasNext()) {
72 Boolean.toString(in.nextBoolean());
86 parseByName(in.nextName(), edit, in, path, schemaTree, edits, patchId);
100 return edits.build();
104 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
106 * @param name value of token
107 * @param edit PatchEdit instance
108 * @param in JsonReader reader
109 * @param path InstanceIdentifierContext context
110 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
111 * @param resultCollection collection of parsed edits
112 * @throws IOException if operation fails
114 private static void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
115 final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext path,
116 final @NonNull DataSchemaContextTree schemaTree,
117 final ImmutableList.@NonNull Builder<PatchEntity> resultCollection,
118 final @NonNull AtomicReference<String> patchId) throws IOException {
121 if (in.peek() == JsonToken.BEGIN_ARRAY) {
124 while (in.hasNext()) {
125 readEditDefinition(edit, in, path, schemaTree);
126 resultCollection.add(prepareEditOperation(edit));
132 readEditDefinition(edit, in, path, schemaTree);
133 resultCollection.add(prepareEditOperation(edit));
139 patchId.set(in.nextString());
147 * Read one patch edit object from Json input.
149 * @param edit PatchEdit instance to be filled with read data
150 * @param in JsonReader reader
151 * @param path InstanceIdentifierContext path context
152 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
153 * @throws IOException if operation fails
155 private static void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
156 final @NonNull InstanceIdentifierContext path, final @NonNull DataSchemaContextTree schemaTree)
158 String deferredValue = null;
161 while (in.hasNext()) {
162 final String editDefinition = in.nextName();
163 switch (editDefinition) {
165 edit.setId(in.nextString());
168 edit.setOperation(Operation.ofName(in.nextString()));
171 // target can be specified completely in request URI
172 edit.setTarget(parsePatchTarget(path, in.nextString()));
173 final var stack = schemaTree.enterPath(edit.getTarget()).orElseThrow().stack();
174 if (!stack.isEmpty()) {
178 if (!stack.isEmpty()) {
179 final EffectiveStatement<?, ?> parentStmt = stack.currentStatement();
180 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
182 edit.setTargetSchemaNode(stack.toInference());
186 checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
188 if (edit.getTargetSchemaNode() == null) {
189 // save data defined in value node for next (later) processing, because target needs to be read
190 // always first and there is no ordering in Json input
191 deferredValue = readValueNode(in);
193 // We have a target schema node, reuse this reader without buffering the value.
194 edit.setData(readEditData(in, edit.getTargetSchemaNode(), path));
198 // FIXME: this does not look right, as it can wreck our logic
205 if (deferredValue != null) {
206 // read saved data to normalized node when target schema is already known
207 edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
213 * Parse data defined in value node and saves it to buffer.
214 * @param sb Buffer to read value node
215 * @param in JsonReader reader
216 * @throws IOException if operation fails
218 private static String readValueNode(final @NonNull JsonReader in) throws IOException {
220 final StringBuilder sb = new StringBuilder().append("{\"").append(in.nextName()).append("\":");
227 while (in.hasNext()) {
228 if (in.peek() == JsonToken.STRING) {
229 sb.append('"').append(in.nextString()).append('"');
231 readValueObject(sb, in);
233 if (in.peek() != JsonToken.END_ARRAY) {
242 readValueObject(sb, in);
247 return sb.append('}').toString();
251 * Parse one value object of data and saves it to buffer.
252 * @param sb Buffer to read value object
253 * @param in JsonReader reader
254 * @throws IOException if operation fails
256 private static void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in)
258 // read simple leaf value
259 if (in.peek() == JsonToken.STRING) {
260 sb.append('"').append(in.nextString()).append('"');
267 while (in.hasNext()) {
268 sb.append('"').append(in.nextName()).append("\":");
272 sb.append('"').append(in.nextString()).append('"');
278 while (in.hasNext()) {
279 if (in.peek() == JsonToken.STRING) {
280 sb.append('"').append(in.nextString()).append('"');
282 readValueObject(sb, in);
285 if (in.peek() != JsonToken.END_ARRAY) {
294 readValueObject(sb, in);
297 if (in.peek() != JsonToken.END_OBJECT) {
307 * Read patch edit data defined in value node to NormalizedNode.
308 * @param in reader JsonReader reader
309 * @return NormalizedNode representing data
311 private static NormalizedNode readEditData(final @NonNull JsonReader in, final @NonNull Inference targetSchemaNode,
312 final @NonNull InstanceIdentifierContext path) {
313 final var resultHolder = new NormalizationResultHolder();
314 final var writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
315 JsonParserStream.create(writer, JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()),
316 targetSchemaNode).parse(in);
318 return resultHolder.getResult().data();
322 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
323 * @param edit Instance of PatchEdit
324 * @return PatchEntity Patch entity
326 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
327 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
328 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
329 if (!requiresValue(edit.getOperation())) {
330 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
333 // for lists allow to manipulate with list items through their parent
334 final YangInstanceIdentifier targetNode;
335 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
336 targetNode = edit.getTarget().getParent();
338 targetNode = edit.getTarget();
341 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
344 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
348 * Check if data is present when operation requires it and not present when operation data is not allowed.
349 * @param operation Name of operation
350 * @param hasData Data in edit are present/not present
351 * @return true if data is present when operation requires it or if there are no data when operation does not
352 * allow it, false otherwise
354 private static boolean checkDataPresence(final @NonNull Operation operation, final boolean hasData) {
355 return requiresValue(operation) == hasData;
359 * Helper class representing one patch edit.
361 private static final class PatchEdit {
363 private Operation operation;
364 private YangInstanceIdentifier target;
365 private Inference targetSchemaNode;
366 private NormalizedNode data;
372 void setId(final String id) {
373 this.id = requireNonNull(id);
376 Operation getOperation() {
380 void setOperation(final Operation operation) {
381 this.operation = requireNonNull(operation);
384 YangInstanceIdentifier getTarget() {
388 void setTarget(final YangInstanceIdentifier target) {
389 this.target = requireNonNull(target);
392 Inference getTargetSchemaNode() {
393 return targetSchemaNode;
396 void setTargetSchemaNode(final Inference targetSchemaNode) {
397 this.targetSchemaNode = requireNonNull(targetSchemaNode);
400 NormalizedNode getData() {
404 void setData(final NormalizedNode data) {
405 this.data = requireNonNull(data);
412 targetSchemaNode = null;