Capture ListenersBroker instances
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfDataServiceImpl.java
index 8cc70c152c6956869ec9dfdc0d771b3de8530158..7e085fb191c0143877b2dc0f801e35dcd454013e 100644 (file)
@@ -19,19 +19,20 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.MoreExecutors;
+import java.io.IOException;
+import java.io.InputStream;
 import java.net.URI;
 import java.time.Clock;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 import java.util.concurrent.CancellationException;
 import java.util.concurrent.ExecutionException;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.Encoded;
 import javax.ws.rs.GET;
+import javax.ws.rs.PATCH;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
 import javax.ws.rs.Path;
@@ -44,6 +45,8 @@ import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 import javax.ws.rs.core.UriInfo;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.mdsal.dom.api.DOMActionException;
 import org.opendaylight.mdsal.dom.api.DOMActionResult;
@@ -56,13 +59,23 @@ import org.opendaylight.mdsal.dom.api.DOMMountPointService;
 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.restconf.common.patch.Patch;
 import org.opendaylight.restconf.common.patch.PatchContext;
 import org.opendaylight.restconf.common.patch.PatchStatusContext;
 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
 import org.opendaylight.restconf.nb.rfc8040.ReadDataParams;
-import org.opendaylight.restconf.nb.rfc8040.WriteDataParams;
+import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindProvider;
+import org.opendaylight.restconf.nb.rfc8040.databind.JsonChildBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.JsonOperationInputBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.JsonPatchBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.JsonResourceBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.XmlChildBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.XmlOperationInputBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.XmlPatchBody;
+import org.opendaylight.restconf.nb.rfc8040.databind.XmlResourceBody;
 import org.opendaylight.restconf.nb.rfc8040.databind.jaxrs.QueryParams;
 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
@@ -78,8 +91,8 @@ import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants
 import org.opendaylight.restconf.nb.rfc8040.streams.StreamsConfiguration;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
+import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.restconf.restconf.Data;
 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
 import org.opendaylight.yangtools.yang.common.Empty;
 import org.opendaylight.yangtools.yang.common.ErrorTag;
@@ -88,15 +101,13 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
 import org.slf4j.Logger;
@@ -118,6 +129,7 @@ public final class RestconfDataServiceImpl {
     private final SubscribeToStreamUtil streamUtils;
     private final DOMActionService actionService;
     private final DOMDataBroker dataBroker;
+    private final ListenersBroker listenersBroker = ListenersBroker.getInstance();
 
     public RestconfDataServiceImpl(final DatabindProvider databindProvider,
             final DOMDataBroker dataBroker, final DOMMountPointService  mountPointService,
@@ -235,9 +247,9 @@ public final class RestconfDataServiceImpl {
                 final var notifName = notification.argument();
 
                 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
-                    createYangNotifiStream(moduleName, notifName, NotificationOutputType.XML));
+                    createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.XML));
                 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
-                    createYangNotifiStream(moduleName, notifName, NotificationOutputType.JSON));
+                    createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.JSON));
             });
         }
 
@@ -248,10 +260,9 @@ public final class RestconfDataServiceImpl {
         }
     }
 
-    private static NotificationListenerAdapter createYangNotifiStream(final String moduleName, final QName notifName,
-            final NotificationOutputType outputType) {
+    private static NotificationListenerAdapter createYangNotifiStream(final ListenersBroker listenersBroker,
+            final String moduleName, final QName notifName, final NotificationOutputType outputType) {
         final var streamName = createNotificationStreamName(moduleName, notifName.getLocalName(), outputType);
-        final var listenersBroker = ListenersBroker.getInstance();
 
         final var existing = listenersBroker.notificationListenerFor(streamName);
         return existing != null ? existing
@@ -279,50 +290,124 @@ public final class RestconfDataServiceImpl {
             RestconfStateStreams.restconfStateStreamPath(mapToStreams.name()), mapToStreams);
     }
 
+    /**
+     * Replace the data store.
+     *
+     * @param uriInfo request URI information
+     * @param body data node for put to config DS
+     * @return {@link Response}
+     */
+    @PUT
+    @Path("/data")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaType.APPLICATION_JSON,
+    })
+    public Response putDataJSON(@Context final UriInfo uriInfo, final InputStream body) {
+        try (var jsonBody = new JsonResourceBody(body)) {
+            return putData(null, uriInfo, jsonBody);
+        }
+    }
+
     /**
      * Create or replace the target data resource.
      *
      * @param identifier path to target
-     * @param payload data node for put to config DS
+     * @param uriInfo request URI information
+     * @param body data node for put to config DS
      * @return {@link Response}
      */
     @PUT
     @Path("/data/{identifier:.+}")
     @Consumes({
         MediaTypes.APPLICATION_YANG_DATA_JSON,
-        MediaTypes.APPLICATION_YANG_DATA_XML,
         MediaType.APPLICATION_JSON,
+    })
+    public Response putDataJSON(@Encoded @PathParam("identifier") final String identifier,
+            @Context final UriInfo uriInfo, final InputStream body) {
+        try (var jsonBody = new JsonResourceBody(body)) {
+            return putData(identifier, uriInfo, jsonBody);
+        }
+    }
+
+    /**
+     * Replace the data store.
+     *
+     * @param uriInfo request URI information
+     * @param body data node for put to config DS
+     * @return {@link Response}
+     */
+    @PUT
+    @Path("/data")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_XML,
         MediaType.APPLICATION_XML,
         MediaType.TEXT_XML
     })
-    public Response putData(@Encoded @PathParam("identifier") final String identifier,
-            final NormalizedNodePayload payload, @Context final UriInfo uriInfo) {
-        requireNonNull(payload);
-
-        final WriteDataParams params = QueryParams.newWriteDataParams(uriInfo);
+    public Response putDataXML(@Context final UriInfo uriInfo, final InputStream body) {
+        try (var xmlBody = new XmlResourceBody(body)) {
+            return putData(null, uriInfo, xmlBody);
+        }
+    }
 
-        final InstanceIdentifierContext iid = payload.getInstanceIdentifierContext();
-        final YangInstanceIdentifier path = iid.getInstanceIdentifier();
+    /**
+     * Create or replace the target data resource.
+     *
+     * @param identifier path to target
+     * @param uriInfo request URI information
+     * @param body data node for put to config DS
+     * @return {@link Response}
+     */
+    @PUT
+    @Path("/data/{identifier:.+}")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_XML,
+        MediaType.APPLICATION_XML,
+        MediaType.TEXT_XML
+    })
+    public Response putDataXML(@Encoded @PathParam("identifier") final String identifier,
+            @Context final UriInfo uriInfo, final InputStream body) {
+        try (var xmlBody = new XmlResourceBody(body)) {
+            return putData(identifier, uriInfo, xmlBody);
+        }
+    }
 
-        validInputData(iid.getSchemaNode() != null, payload);
-        validTopLevelNodeName(path, payload);
-        validateListKeysEqualityInPayloadAndUri(payload);
+    private Response putData(final @Nullable String identifier, final UriInfo uriInfo, final ResourceBody body) {
+        final var params = QueryParams.newWriteDataParams(uriInfo);
+        final var req = bindResourceRequest(identifier, body);
 
-        final var strategy = getRestconfStrategy(iid.getMountPoint());
-        final var result = PutDataTransactionUtil.putData(path, payload.getData(), iid.getSchemaContext(), strategy,
-            params);
-        return switch (result) {
+        return switch (
+            PutDataTransactionUtil.putData(req.path(), req.data(), req.modelContext(), req.strategy(), params)) {
             // Note: no Location header, as it matches the request path
             case CREATED -> Response.status(Status.CREATED).build();
             case REPLACED -> Response.noContent().build();
         };
     }
 
+    /**
+     * Create a top-level data resource.
+     *
+     * @param body data node for put to config DS
+     * @param uriInfo URI info
+     * @return {@link Response}
+     */
+    @POST
+    @Path("/data/{identifier:.+}")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaType.APPLICATION_JSON,
+    })
+    public Response postDataJSON(final InputStream body, @Context final UriInfo uriInfo) {
+        try (var jsonBody = new JsonChildBody(body)) {
+            return postData(jsonBody, uriInfo);
+        }
+    }
+
     /**
      * Create a data resource in target.
      *
      * @param identifier path to target
-     * @param payload new data
+     * @param body data node for put to config DS
      * @param uriInfo URI info
      * @return {@link Response}
      */
@@ -330,43 +415,113 @@ public final class RestconfDataServiceImpl {
     @Path("/data/{identifier:.+}")
     @Consumes({
         MediaTypes.APPLICATION_YANG_DATA_JSON,
-        MediaTypes.APPLICATION_YANG_DATA_XML,
         MediaType.APPLICATION_JSON,
+    })
+    public Response postDataJSON(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
+            @Context final UriInfo uriInfo) {
+        final var instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier,
+            databindProvider.currentContext().modelContext(), mountPointService);
+        if (instanceIdentifier.getSchemaNode() instanceof ActionDefinition) {
+            try (var jsonBody = new JsonOperationInputBody(body)) {
+                return invokeAction(instanceIdentifier, jsonBody);
+            }
+        }
+
+        try (var jsonBody = new JsonChildBody(body)) {
+            return postData(instanceIdentifier, jsonBody, uriInfo);
+        }
+    }
+
+    /**
+     * Create a top-level data resource.
+     *
+     * @param body data node for put to config DS
+     * @param uriInfo URI info
+     * @return {@link Response}
+     */
+    @POST
+    @Path("/data")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_XML,
         MediaType.APPLICATION_XML,
         MediaType.TEXT_XML
     })
-    public Response postData(@Encoded @PathParam("identifier") final String identifier,
-            final NormalizedNodePayload payload, @Context final UriInfo uriInfo) {
-        return postData(payload, uriInfo);
+    public Response postDataXML(final InputStream body, @Context final UriInfo uriInfo) {
+        try (var xmlBody = new XmlChildBody(body)) {
+            return postData(xmlBody, uriInfo);
+        }
     }
 
     /**
-     * Create a data resource.
+     * Create a data resource in target.
      *
-     * @param payload new data
+     * @param identifier path to target
+     * @param body data node for put to config DS
      * @param uriInfo URI info
      * @return {@link Response}
      */
     @POST
-    @Path("/data")
+    @Path("/data/{identifier:.+}")
     @Consumes({
-        MediaTypes.APPLICATION_YANG_DATA_JSON,
         MediaTypes.APPLICATION_YANG_DATA_XML,
-        MediaType.APPLICATION_JSON,
         MediaType.APPLICATION_XML,
         MediaType.TEXT_XML
     })
-    public Response postData(final NormalizedNodePayload payload, @Context final UriInfo uriInfo) {
-        requireNonNull(payload);
-        final InstanceIdentifierContext iid = payload.getInstanceIdentifierContext();
-        if (iid.getSchemaNode() instanceof ActionDefinition) {
-            return invokeAction(payload);
+    public Response postDataXML(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
+            @Context final UriInfo uriInfo) {
+        final var instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier,
+            databindProvider.currentContext().modelContext(), mountPointService);
+        if (instanceIdentifier.getSchemaNode() instanceof ActionDefinition) {
+            try (var xmlBody = new XmlOperationInputBody(body)) {
+                return invokeAction(instanceIdentifier, xmlBody);
+            }
+        }
+
+        try (var xmlBody = new XmlChildBody(body)) {
+            return postData(instanceIdentifier, xmlBody, uriInfo);
+        }
+    }
+
+    private Response postData(final ChildBody body, final UriInfo uriInfo) {
+        return postData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()), body,
+            uriInfo);
+    }
+
+    private Response postData(final InstanceIdentifierContext iid, final ChildBody body, final UriInfo uriInfo) {
+        final var params = QueryParams.newWriteDataParams(uriInfo);
+        final var strategy = getRestconfStrategy(iid.getMountPoint());
+        final var context = iid.getSchemaContext();
+        var path = iid.getInstanceIdentifier();
+        final var payload = body.toPayload(path, iid.inference());
+        final var data = payload.body();
+
+        for (var arg : payload.prefix()) {
+            path = path.node(arg);
+        }
+
+        PostDataTransactionUtil.postData(path, data, strategy, context, params);
+        return Response.created(resolveLocation(uriInfo, path, context, data)).build();
+    }
+
+    /**
+     * Get location from {@link YangInstanceIdentifier} and {@link UriInfo}.
+     *
+     * @param uriInfo       uri info
+     * @param initialPath   data path
+     * @param schemaContext reference to {@link SchemaContext}
+     * @return {@link URI}
+     */
+    private static URI resolveLocation(final UriInfo uriInfo, final YangInstanceIdentifier initialPath,
+                                       final EffectiveModelContext schemaContext, final NormalizedNode data) {
+        YangInstanceIdentifier path = initialPath;
+        if (data instanceof MapNode mapData) {
+            final var children = mapData.body();
+            if (!children.isEmpty()) {
+                path = path.node(children.iterator().next().name());
+            }
         }
 
-        final WriteDataParams params = QueryParams.newWriteDataParams(uriInfo);
-        final RestconfStrategy strategy = getRestconfStrategy(iid.getMountPoint());
-        return PostDataTransactionUtil.postData(uriInfo, iid.getInstanceIdentifier(), payload.getData(), strategy,
-            iid.getSchemaContext(), params);
+        return uriInfo.getBaseUriBuilder().path("data").path(IdentifierCodec.serialize(path, schemaContext)).build();
     }
 
     /**
@@ -397,81 +552,100 @@ public final class RestconfDataServiceImpl {
     }
 
     /**
-     * Ordered list of edits that are applied to the target datastore by the server.
+     * Partially modify the target data store, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
+     *
+     * @param body data node for put to config DS
+     * @param ar {@link AsyncResponse} which needs to be completed
+     */
+    @PATCH
+    @Path("/data")
+    @Consumes({
+        MediaTypes.APPLICATION_YANG_DATA_XML,
+        MediaType.APPLICATION_XML,
+        MediaType.TEXT_XML
+    })
+    public void plainPatchDataXML(final InputStream body, @Suspended final AsyncResponse ar) {
+        try (var xmlBody = new XmlResourceBody(body)) {
+            plainPatchData(null, xmlBody, ar);
+        }
+    }
+
+    /**
+     * Partially modify the target data resource, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
      *
      * @param identifier path to target
-     * @param context edits
-     * @param uriInfo URI info
-     * @return {@link PatchStatusContext}
+     * @param body data node for put to config DS
+     * @param ar {@link AsyncResponse} which needs to be completed
      */
-    @Patch
+    @PATCH
     @Path("/data/{identifier:.+}")
     @Consumes({
-        MediaTypes.APPLICATION_YANG_PATCH_JSON,
-        MediaTypes.APPLICATION_YANG_PATCH_XML
-    })
-    @Produces({
-        MediaTypes.APPLICATION_YANG_DATA_JSON,
-        MediaTypes.APPLICATION_YANG_DATA_XML
+        MediaTypes.APPLICATION_YANG_DATA_XML,
+        MediaType.APPLICATION_XML,
+        MediaType.TEXT_XML
     })
-    public PatchStatusContext patchData(@Encoded @PathParam("identifier") final String identifier,
-            final PatchContext context, @Context final UriInfo uriInfo) {
-        return patchData(context, uriInfo);
+    public void plainPatchDataXML(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
+            @Suspended final AsyncResponse ar) {
+        try (var xmlBody = new XmlResourceBody(body)) {
+            plainPatchData(identifier, xmlBody, ar);
+        }
     }
 
     /**
-     * Ordered list of edits that are applied to the datastore by the server.
+     * Partially modify the target data store, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
      *
-     * @param context
-     *            edits
-     * @param uriInfo
-     *            URI info
-     * @return {@link PatchStatusContext}
+     * @param body data node for put to config DS
+     * @param ar {@link AsyncResponse} which needs to be completed
      */
-    @Patch
+    @PATCH
     @Path("/data")
     @Consumes({
-        MediaTypes.APPLICATION_YANG_PATCH_JSON,
-        MediaTypes.APPLICATION_YANG_PATCH_XML
-    })
-    @Produces({
         MediaTypes.APPLICATION_YANG_DATA_JSON,
-        MediaTypes.APPLICATION_YANG_DATA_XML
+        MediaType.APPLICATION_JSON,
     })
-    public PatchStatusContext patchData(final PatchContext context, @Context final UriInfo uriInfo) {
-        final InstanceIdentifierContext iid = RestconfDocumentedException.throwIfNull(context,
-            ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "No patch documented provided")
-            .getInstanceIdentifierContext();
-        final RestconfStrategy strategy = getRestconfStrategy(iid.getMountPoint());
-        return PatchDataTransactionUtil.patchData(context, strategy, iid.getSchemaContext());
+    public void plainPatchDataJSON(final InputStream body, @Suspended final AsyncResponse ar) {
+        try (var jsonBody = new JsonResourceBody(body)) {
+            plainPatchData(null, jsonBody, ar);
+        }
     }
 
     /**
-     * Partially modify the target data resource.
+     * Partially modify the target data resource, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
      *
      * @param identifier path to target
-     * @param payload data node for put to config DS
+     * @param body data node for put to config DS
      * @param ar {@link AsyncResponse} which needs to be completed
      */
-    @Patch
+    @PATCH
     @Path("/data/{identifier:.+}")
     @Consumes({
         MediaTypes.APPLICATION_YANG_DATA_JSON,
-        MediaTypes.APPLICATION_YANG_DATA_XML,
         MediaType.APPLICATION_JSON,
-        MediaType.APPLICATION_XML,
-        MediaType.TEXT_XML
     })
-    public void patchData(@Encoded @PathParam("identifier") final String identifier,
-            final NormalizedNodePayload payload, @Context final UriInfo uriInfo, @Suspended final AsyncResponse ar) {
-        final InstanceIdentifierContext iid = payload.getInstanceIdentifierContext();
-        final YangInstanceIdentifier path = iid.getInstanceIdentifier();
-        validInputData(iid.getSchemaNode() != null, payload);
-        validTopLevelNodeName(path, payload);
-        validateListKeysEqualityInPayloadAndUri(payload);
-        final var strategy = getRestconfStrategy(iid.getMountPoint());
+    public void plainPatchDataJSON(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
+            @Suspended final AsyncResponse ar) {
+        try (var jsonBody = new JsonResourceBody(body)) {
+            plainPatchData(identifier, jsonBody, ar);
+        }
+    }
+
+    /**
+     * Partially modify the target data resource, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
+     *
+     * @param identifier path to target
+     * @param body data node for put to config DS
+     * @param ar {@link AsyncResponse} which needs to be completed
+     */
+    private void plainPatchData(final @Nullable String identifier, final ResourceBody body, final AsyncResponse ar) {
+        final var req = bindResourceRequest(identifier, body);
+        final var future = req.strategy().merge(req.path(), req.data(), req.modelContext());
 
-        Futures.addCallback(strategy.merge(path, payload.getData(), iid.getSchemaContext()), new FutureCallback<>() {
+        Futures.addCallback(future, new FutureCallback<>() {
             @Override
             public void onSuccess(final Empty result) {
                 ar.resume(Response.ok().build());
@@ -484,6 +658,129 @@ public final class RestconfDataServiceImpl {
         }, MoreExecutors.directExecutor());
     }
 
+    private @NonNull ResourceRequest bindResourceRequest(final @Nullable String identifier, final ResourceBody body) {
+        final var dataBind = databindProvider.currentContext();
+        final var context = ParserIdentifier.toInstanceIdentifier(identifier, dataBind.modelContext(),
+            mountPointService);
+        final var inference = context.inference();
+        final var path = context.getInstanceIdentifier();
+        final var data = body.toNormalizedNode(path, inference, context.getSchemaNode());
+
+        return new ResourceRequest(getRestconfStrategy(context.getMountPoint()), inference.getEffectiveModelContext(),
+            path, data);
+    }
+
+    /**
+     * Ordered list of edits that are applied to the target datastore by the server, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
+     *
+     * @param identifier path to target
+     * @param body YANG Patch body
+     * @return {@link PatchStatusContext}
+     */
+    @PATCH
+    @Path("/data/{identifier:.+}")
+    @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
+    @Produces({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaTypes.APPLICATION_YANG_DATA_XML
+    })
+    public PatchStatusContext yangPatchDataXML(@Encoded @PathParam("identifier") final String identifier,
+            final InputStream body) {
+        try (var xmlBody = new XmlPatchBody(body)) {
+            return yangPatchData(identifier, xmlBody);
+        }
+    }
+
+    /**
+     * Ordered list of edits that are applied to the datastore by the server, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
+     *
+     * @param body YANG Patch body
+     * @return {@link PatchStatusContext}
+     */
+    @PATCH
+    @Path("/data")
+    @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
+    @Produces({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaTypes.APPLICATION_YANG_DATA_XML
+    })
+    public PatchStatusContext yangPatchDataXML(final InputStream body) {
+        try (var xmlBody = new XmlPatchBody(body)) {
+            return yangPatchData(xmlBody);
+        }
+    }
+
+    /**
+     * Ordered list of edits that are applied to the target datastore by the server, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
+     *
+     * @param identifier path to target
+     * @param body YANG Patch body
+     * @return {@link PatchStatusContext}
+     */
+    @PATCH
+    @Path("/data/{identifier:.+}")
+    @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
+    @Produces({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaTypes.APPLICATION_YANG_DATA_XML
+    })
+    public PatchStatusContext yangPatchDataJSON(@Encoded @PathParam("identifier") final String identifier,
+            final InputStream body) {
+        try (var jsonBody = new JsonPatchBody(body)) {
+            return yangPatchData(identifier, jsonBody);
+        }
+    }
+
+    /**
+     * Ordered list of edits that are applied to the datastore by the server, as defined in
+     * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
+     *
+     * @param body YANG Patch body
+     * @return {@link PatchStatusContext}
+     */
+    @PATCH
+    @Path("/data")
+    @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
+    @Produces({
+        MediaTypes.APPLICATION_YANG_DATA_JSON,
+        MediaTypes.APPLICATION_YANG_DATA_XML
+    })
+    public PatchStatusContext yangPatchDataJSON(final InputStream body) {
+        try (var jsonBody = new JsonPatchBody(body)) {
+            return yangPatchData(jsonBody);
+        }
+    }
+
+    private PatchStatusContext yangPatchData(final @NonNull PatchBody body) {
+        return yangPatchData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()),
+            body);
+    }
+
+    private PatchStatusContext yangPatchData(final String identifier, final @NonNull PatchBody body) {
+        return yangPatchData(ParserIdentifier.toInstanceIdentifier(identifier,
+                databindProvider.currentContext().modelContext(), mountPointService), body);
+    }
+
+    private PatchStatusContext yangPatchData(final @NonNull InstanceIdentifierContext targetResource,
+            final @NonNull PatchBody body) {
+        try {
+            return yangPatchData(targetResource, body.toPatchContext(targetResource));
+        } catch (IOException e) {
+            LOG.debug("Error parsing YANG Patch input", e);
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE, e);
+        }
+    }
+
+    @VisibleForTesting
+    PatchStatusContext yangPatchData(final InstanceIdentifierContext targetResource, final PatchContext context) {
+        return PatchDataTransactionUtil.patchData(context, getRestconfStrategy(targetResource.getMountPoint()),
+            targetResource.getSchemaContext());
+    }
+
     @VisibleForTesting
     RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
         if (mountPoint == null) {
@@ -503,38 +800,28 @@ public final class RestconfDataServiceImpl {
      * @param payload {@link NormalizedNodePayload} - the body of the operation
      * @return {@link NormalizedNodePayload} wrapped in {@link Response}
      */
-    public Response invokeAction(final NormalizedNodePayload payload) {
-        final InstanceIdentifierContext context = payload.getInstanceIdentifierContext();
-        final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
-        final NormalizedNode data = payload.getData();
-
-        if (yangIIdContext.isEmpty() && !Data.QNAME.equals(data.name().getNodeType())) {
-            throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
-                ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
-        }
-
-        final DOMMountPoint mountPoint = context.getMountPoint();
-        final Absolute schemaPath = context.inference().toSchemaInferenceStack().toSchemaNodeIdentifier();
-        final DOMActionResult response;
-        if (mountPoint != null) {
-            response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, mountPoint);
-        } else {
-            response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, actionService);
+    private Response invokeAction(final InstanceIdentifierContext context, final OperationInputBody body) {
+        final var yangIIdContext = context.getInstanceIdentifier();
+        final ContainerNode input;
+        try {
+            input = body.toContainerNode(context.inference());
+        } catch (IOException e) {
+            LOG.debug("Error reading input", e);
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE, e);
         }
-        final DOMActionResult result = checkActionResponse(response);
 
-        ContainerNode resultData = null;
-        if (result != null) {
-            resultData = result.getOutput().orElse(null);
-        }
+        final var mountPoint = context.getMountPoint();
+        final var schemaPath = context.inference().toSchemaInferenceStack().toSchemaNodeIdentifier();
+        final var response = mountPoint != null ? invokeAction(input, schemaPath, yangIIdContext, mountPoint)
+            : invokeAction(input, schemaPath, yangIIdContext, actionService);
+        final var result = checkActionResponse(response);
 
+        final var resultData = result != null ? result.getOutput().orElse(null) : null;
         if (resultData != null && resultData.isEmpty()) {
             return Response.status(Status.NO_CONTENT).build();
         }
-
-        return Response.status(Status.OK)
-            .entity(NormalizedNodePayload.ofNullable(context, resultData))
-            .build();
+        return Response.status(Status.OK).entity(NormalizedNodePayload.ofNullable(context, resultData)).build();
     }
 
     /**
@@ -594,88 +881,4 @@ public final class RestconfDataServiceImpl {
             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
         }
     }
-
-    /**
-     * Valid input data based on presence of a schema node.
-     *
-     * @param haveSchemaNode true if there is an underlying schema node
-     * @param payload    input data
-     */
-    @VisibleForTesting
-    static void validInputData(final boolean haveSchemaNode, final NormalizedNodePayload payload) {
-        final boolean haveData = payload.getData() != null;
-        if (haveSchemaNode) {
-            if (!haveData) {
-                throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE);
-            }
-        } else if (haveData) {
-            throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
-        }
-    }
-
-    /**
-     * Valid top level node name.
-     *
-     * @param path    path of node
-     * @param payload data
-     */
-    @VisibleForTesting
-    static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodePayload payload) {
-        final QName dataNodeType = payload.getData().name().getNodeType();
-        if (path.isEmpty()) {
-            if (!Data.QNAME.equals(dataNodeType)) {
-                throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
-                        ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
-            }
-        } else {
-            final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
-            final String payloadName = dataNodeType.getLocalName();
-            if (!payloadName.equals(identifierName)) {
-                throw new RestconfDocumentedException(
-                        "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
-                        ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
-            }
-        }
-    }
-
-    /**
-     * Validates whether keys in {@code payload} are equal to values of keys in
-     * {@code iiWithData} for list schema node.
-     *
-     * @throws RestconfDocumentedException if key values or key count in payload and URI isn't equal
-     */
-    @VisibleForTesting
-    static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodePayload payload) {
-        final InstanceIdentifierContext iiWithData = payload.getInstanceIdentifierContext();
-        final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
-        final SchemaNode schemaNode = iiWithData.getSchemaNode();
-        final NormalizedNode data = payload.getData();
-        if (schemaNode instanceof ListSchemaNode listSchema) {
-            final var keyDefinitions = listSchema.getKeyDefinition();
-            if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
-                final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
-                isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
-            }
-        }
-    }
-
-    private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
-            final List<QName> keyDefinitions) {
-        final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
-        for (final QName keyDefinition : keyDefinitions) {
-            final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
-                    mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
-                    "Missing key %s in URI.", keyDefinition);
-
-            final Object dataKeyValue = payload.name().getValue(keyDefinition);
-
-            if (!uriKeyValue.equals(dataKeyValue)) {
-                final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
-                        + "' specified in the URI doesn't match the value '" + dataKeyValue
-                        + "' specified in the message body. ";
-                throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
-            }
-        }
-    }
 }