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.server.api;
10 import static com.google.common.base.Verify.verify;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.text.ParseException;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.restconf.api.ApiPath;
17 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
18 import org.opendaylight.restconf.common.patch.PatchContext;
19 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
21 import org.opendaylight.yangtools.yang.common.ErrorTag;
22 import org.opendaylight.yangtools.yang.common.ErrorType;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 public abstract sealed class PatchBody extends AbstractBody permits JsonPatchBody, XmlPatchBody {
29 PatchBody(final InputStream inputStream) {
33 public final @NonNull PatchContext toPatchContext(final DatabindPath.@NonNull Data path) throws IOException {
34 try (var is = acquireStream()) {
35 return toPatchContext(path, is);
39 abstract @NonNull PatchContext toPatchContext(DatabindPath.@NonNull Data path, @NonNull InputStream inputStream)
42 static final YangInstanceIdentifier parsePatchTarget(final DatabindPath.@NonNull Data path, final String target) {
43 final var urlPath = path.instance();
44 if (target.equals("/")) {
45 verify(!urlPath.isEmpty(),
46 "target resource of URI must not be a datastore resource when target is '/'");
50 // FIXME: NETCONF-1157: these two operations should really be a single ApiPathNormalizer step -- but for that
51 // we need to switch to ApiPath forms
52 final var pathNormalizer = new ApiPathNormalizer(path.databind());
53 final String targetUrl;
54 if (urlPath.isEmpty()) {
55 targetUrl = target.startsWith("/") ? target.substring(1) : target;
57 targetUrl = pathNormalizer.canonicalize(urlPath).toString() + target;
61 return pathNormalizer.normalizeDataPath(ApiPath.parse(targetUrl)).instance();
62 } catch (ParseException | RestconfDocumentedException e) {
63 throw new RestconfDocumentedException("Failed to parse target " + target,
64 ErrorType.RPC, ErrorTag.MALFORMED_MESSAGE, e);
69 * Not all patch operations support value node. Check if operation requires value or not.
71 * @param operation Patch edit operation
72 * @return true if operation requires value, false otherwise
74 static final boolean requiresValue(final Operation operation) {
75 return switch (operation) {
76 case Create, Insert, Merge, Replace -> true;
77 case Delete, Move, Remove -> false;