2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.restconf.nb.rfc8040.databind;
10 import static com.google.common.base.Verify.verify;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
16 import org.opendaylight.restconf.common.patch.PatchContext;
17 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
18 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
19 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 public abstract sealed class PatchBody extends AbstractBody permits JsonPatchBody, XmlPatchBody {
26 PatchBody(final InputStream inputStream) {
30 public final @NonNull PatchContext toPatchContext(final @NonNull InstanceIdentifierContext targetResource)
32 try (var is = acquireStream()) {
33 return toPatchContext(targetResource, is);
37 abstract @NonNull PatchContext toPatchContext(@NonNull InstanceIdentifierContext targetResource,
38 @NonNull InputStream inputStream) throws IOException;
40 static final YangInstanceIdentifier parsePatchTarget(final InstanceIdentifierContext targetResource,
41 final String target) {
42 final var urlPath = targetResource.getInstanceIdentifier();
43 if (target.equals("/")) {
44 verify(!urlPath.isEmpty(),
45 "target resource of URI must not be a datastore resource when target is '/'");
49 final var schemaContext = targetResource.getSchemaContext();
50 final String targetUrl;
51 if (urlPath.isEmpty()) {
52 targetUrl = target.startsWith("/") ? target.substring(1) : target;
54 targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
57 return ParserIdentifier.toInstanceIdentifier(targetUrl, schemaContext, null).getInstanceIdentifier();
61 * Not all patch operations support value node. Check if operation requires value or not.
63 * @param operation Patch edit operation
64 * @return true if operation requires value, false otherwise
66 static final boolean requiresValue(final Operation operation) {
67 return switch (operation) {
68 case Create, Insert, Merge, Replace -> true;
69 case Delete, Move, Remove -> false;