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.server.api;
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.common.collect.ImmutableList.Builder;
17 import com.google.gson.stream.JsonReader;
18 import com.google.gson.stream.JsonToken;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.StringReader;
23 import java.nio.charset.StandardCharsets;
24 import java.util.concurrent.atomic.AtomicReference;
25 import org.eclipse.jdt.annotation.NonNull;
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.JSONCodecFactory;
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.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
42 public final class JsonPatchBody extends PatchBody {
43 public JsonPatchBody(final InputStream inputStream) {
48 PatchContext toPatchContext(final ResourceContext resource, final InputStream inputStream) throws IOException {
49 try (var jsonReader = new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
50 final var patchId = new AtomicReference<String>();
51 final var resultList = read(jsonReader, resource, patchId);
52 // Note: patchId side-effect of above
53 return new PatchContext(patchId.get(), resultList);
57 private static ImmutableList<PatchEntity> read(final JsonReader in, final @NonNull ResourceContext resource,
58 final AtomicReference<String> patchId) throws IOException {
59 final var edits = ImmutableList.<PatchEntity>builder();
60 final var edit = new PatchEdit();
62 while (in.hasNext()) {
69 Boolean.toString(in.nextBoolean());
83 parseByName(in.nextName(), edit, in, resource, edits, patchId);
100 // Switch value of parsed JsonToken.NAME and read edit definition or patch id
101 private static void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
102 final @NonNull JsonReader in, final @NonNull ResourceContext resource,
103 final @NonNull Builder<PatchEntity> resultCollection, final @NonNull AtomicReference<String> patchId)
107 if (in.peek() == JsonToken.BEGIN_ARRAY) {
110 while (in.hasNext()) {
111 readEditDefinition(edit, in, resource);
112 resultCollection.add(prepareEditOperation(edit));
118 readEditDefinition(edit, in, resource);
119 resultCollection.add(prepareEditOperation(edit));
125 patchId.set(in.nextString());
132 // Read one patch edit object from JSON input
133 private static void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
134 final @NonNull ResourceContext resource) throws IOException {
135 String deferredValue = null;
138 final var codecs = resource.path.databind().jsonCodecs();
140 while (in.hasNext()) {
141 final String editDefinition = in.nextName();
142 switch (editDefinition) {
144 edit.setId(in.nextString());
147 edit.setOperation(Operation.ofName(in.nextString()));
150 // target can be specified completely in request URI
151 final var target = parsePatchTarget(resource, in.nextString());
152 edit.setTarget(target.instance());
153 final var stack = target.inference().toSchemaInferenceStack();
154 if (!stack.isEmpty()) {
158 if (!stack.isEmpty()) {
159 final var parentStmt = stack.currentStatement();
160 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
162 edit.setTargetSchemaNode(stack.toInference());
166 checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
168 if (edit.getTargetSchemaNode() == null) {
169 // save data defined in value node for next (later) processing, because target needs to be read
170 // always first and there is no ordering in Json input
171 deferredValue = readValueNode(in);
173 // We have a target schema node, reuse this reader without buffering the value.
174 edit.setData(readEditData(in, edit.getTargetSchemaNode(), codecs));
178 // FIXME: this does not look right, as it can wreck our logic
185 if (deferredValue != null) {
186 // read saved data to normalized node when target schema is already known
187 edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
193 * Parse data defined in value node and saves it to buffer.
194 * @param sb Buffer to read value node
195 * @param in JsonReader reader
196 * @throws IOException if operation fails
198 private static String readValueNode(final @NonNull JsonReader in) throws IOException {
200 final StringBuilder sb = new StringBuilder().append("{\"").append(in.nextName()).append("\":");
207 while (in.hasNext()) {
208 if (in.peek() == JsonToken.STRING) {
209 sb.append('"').append(in.nextString()).append('"');
211 readValueObject(sb, in);
213 if (in.peek() != JsonToken.END_ARRAY) {
222 readValueObject(sb, in);
227 return sb.append('}').toString();
231 * Parse one value object of data and saves it to buffer.
232 * @param sb Buffer to read value object
233 * @param in JsonReader reader
234 * @throws IOException if operation fails
236 private static void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in)
238 // read simple leaf value
239 if (in.peek() == JsonToken.STRING) {
240 sb.append('"').append(in.nextString()).append('"');
247 while (in.hasNext()) {
248 sb.append('"').append(in.nextName()).append("\":");
252 sb.append('"').append(in.nextString()).append('"');
258 while (in.hasNext()) {
259 if (in.peek() == JsonToken.STRING) {
260 sb.append('"').append(in.nextString()).append('"');
262 readValueObject(sb, in);
265 if (in.peek() != JsonToken.END_ARRAY) {
274 readValueObject(sb, in);
277 if (in.peek() != JsonToken.END_OBJECT) {
287 * Read patch edit data defined in value node to NormalizedNode.
288 * @param in reader JsonReader reader
289 * @return NormalizedNode representing data
291 private static NormalizedNode readEditData(final @NonNull JsonReader in, final @NonNull Inference targetSchemaNode,
292 final @NonNull JSONCodecFactory codecs) {
293 final var resultHolder = new NormalizationResultHolder();
294 final var writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
295 JsonParserStream.create(writer, codecs, targetSchemaNode).parse(in);
296 return resultHolder.getResult().data();
300 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
301 * @param edit Instance of PatchEdit
302 * @return PatchEntity Patch entity
304 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
305 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
306 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
307 if (!requiresValue(edit.getOperation())) {
308 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
311 // for lists allow to manipulate with list items through their parent
312 final YangInstanceIdentifier targetNode;
313 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
314 targetNode = edit.getTarget().getParent();
316 targetNode = edit.getTarget();
319 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
322 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
326 * Check if data is present when operation requires it and not present when operation data is not allowed.
327 * @param operation Name of operation
328 * @param hasData Data in edit are present/not present
329 * @return true if data is present when operation requires it or if there are no data when operation does not
330 * allow it, false otherwise
332 private static boolean checkDataPresence(final @NonNull Operation operation, final boolean hasData) {
333 return requiresValue(operation) == hasData;
337 * Helper class representing one patch edit.
339 private static final class PatchEdit {
341 private Operation operation;
342 private YangInstanceIdentifier target;
343 private Inference targetSchemaNode;
344 private NormalizedNode data;
350 void setId(final String id) {
351 this.id = requireNonNull(id);
354 Operation getOperation() {
358 void setOperation(final Operation operation) {
359 this.operation = requireNonNull(operation);
362 YangInstanceIdentifier getTarget() {
366 void setTarget(final YangInstanceIdentifier target) {
367 this.target = requireNonNull(target);
370 Inference getTargetSchemaNode() {
371 return targetSchemaNode;
374 void setTargetSchemaNode(final Inference targetSchemaNode) {
375 this.targetSchemaNode = requireNonNull(targetSchemaNode);
378 NormalizedNode getData() {
382 void setData(final NormalizedNode data) {
383 this.data = requireNonNull(data);
390 targetSchemaNode = null;