7e085fb191c0143877b2dc0f801e35dcd454013e
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfDataServiceImpl.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.NOTIFICATION_STREAM;
12 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAMS_PATH;
13 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
14 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
15 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
16 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART;
17
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URI;
25 import java.time.Clock;
26 import java.time.LocalDateTime;
27 import java.time.format.DateTimeFormatter;
28 import java.util.List;
29 import java.util.concurrent.CancellationException;
30 import java.util.concurrent.ExecutionException;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.Encoded;
34 import javax.ws.rs.GET;
35 import javax.ws.rs.PATCH;
36 import javax.ws.rs.POST;
37 import javax.ws.rs.PUT;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.PathParam;
40 import javax.ws.rs.Produces;
41 import javax.ws.rs.container.AsyncResponse;
42 import javax.ws.rs.container.Suspended;
43 import javax.ws.rs.core.Context;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.Status;
47 import javax.ws.rs.core.UriInfo;
48 import org.eclipse.jdt.annotation.NonNull;
49 import org.eclipse.jdt.annotation.Nullable;
50 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
51 import org.opendaylight.mdsal.dom.api.DOMActionException;
52 import org.opendaylight.mdsal.dom.api.DOMActionResult;
53 import org.opendaylight.mdsal.dom.api.DOMActionService;
54 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
55 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
56 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
57 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
58 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
59 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
60 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
61 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
62 import org.opendaylight.restconf.common.patch.PatchContext;
63 import org.opendaylight.restconf.common.patch.PatchStatusContext;
64 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
65 import org.opendaylight.restconf.nb.rfc8040.ReadDataParams;
66 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
67 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindProvider;
68 import org.opendaylight.restconf.nb.rfc8040.databind.JsonChildBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.JsonOperationInputBody;
70 import org.opendaylight.restconf.nb.rfc8040.databind.JsonPatchBody;
71 import org.opendaylight.restconf.nb.rfc8040.databind.JsonResourceBody;
72 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
73 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
74 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
75 import org.opendaylight.restconf.nb.rfc8040.databind.XmlChildBody;
76 import org.opendaylight.restconf.nb.rfc8040.databind.XmlOperationInputBody;
77 import org.opendaylight.restconf.nb.rfc8040.databind.XmlPatchBody;
78 import org.opendaylight.restconf.nb.rfc8040.databind.XmlResourceBody;
79 import org.opendaylight.restconf.nb.rfc8040.databind.jaxrs.QueryParams;
80 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
81 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
82 import org.opendaylight.restconf.nb.rfc8040.monitoring.RestconfStateStreams;
83 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
84 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
85 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
86 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
87 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
88 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
89 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
90 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
91 import org.opendaylight.restconf.nb.rfc8040.streams.StreamsConfiguration;
92 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
93 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
94 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
95 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
96 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
97 import org.opendaylight.yangtools.yang.common.Empty;
98 import org.opendaylight.yangtools.yang.common.ErrorTag;
99 import org.opendaylight.yangtools.yang.common.ErrorType;
100 import org.opendaylight.yangtools.yang.common.QName;
101 import org.opendaylight.yangtools.yang.common.Revision;
102 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
103 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
104 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
108 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
109 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.stmt.NotificationEffectiveStatement;
112 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
113 import org.slf4j.Logger;
114 import org.slf4j.LoggerFactory;
115
116 /**
117  * The "{+restconf}/data" subtree represents the datastore resource type, which is a collection of configuration data
118  * and state data nodes.
119  */
120 @Path("/")
121 public final class RestconfDataServiceImpl {
122     private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
123     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
124
125     private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
126     private final DatabindProvider databindProvider;
127     private final MdsalRestconfStrategy restconfStrategy;
128     private final DOMMountPointService mountPointService;
129     private final SubscribeToStreamUtil streamUtils;
130     private final DOMActionService actionService;
131     private final DOMDataBroker dataBroker;
132     private final ListenersBroker listenersBroker = ListenersBroker.getInstance();
133
134     public RestconfDataServiceImpl(final DatabindProvider databindProvider,
135             final DOMDataBroker dataBroker, final DOMMountPointService  mountPointService,
136             final RestconfStreamsSubscriptionService delegRestconfSubscrService,
137             final DOMActionService actionService, final StreamsConfiguration configuration) {
138         this.databindProvider = requireNonNull(databindProvider);
139         this.dataBroker = requireNonNull(dataBroker);
140         restconfStrategy = new MdsalRestconfStrategy(dataBroker);
141         this.mountPointService = requireNonNull(mountPointService);
142         this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
143         this.actionService = requireNonNull(actionService);
144         streamUtils = configuration.useSSE() ? SubscribeToStreamUtil.serverSentEvents()
145                 : SubscribeToStreamUtil.webSockets();
146     }
147
148     /**
149      * Get target data resource from data root.
150      *
151      * @param uriInfo URI info
152      * @return {@link NormalizedNodePayload}
153      */
154     @GET
155     @Path("/data")
156     @Produces({
157         MediaTypes.APPLICATION_YANG_DATA_JSON,
158         MediaTypes.APPLICATION_YANG_DATA_XML,
159         MediaType.APPLICATION_JSON,
160         MediaType.APPLICATION_XML,
161         MediaType.TEXT_XML
162     })
163     public Response readData(@Context final UriInfo uriInfo) {
164         return readData(null, uriInfo);
165     }
166
167     /**
168      * Get target data resource.
169      *
170      * @param identifier path to target
171      * @param uriInfo URI info
172      * @return {@link NormalizedNodePayload}
173      */
174     @GET
175     @Path("/data/{identifier:.+}")
176     @Produces({
177         MediaTypes.APPLICATION_YANG_DATA_JSON,
178         MediaTypes.APPLICATION_YANG_DATA_XML,
179         MediaType.APPLICATION_JSON,
180         MediaType.APPLICATION_XML,
181         MediaType.TEXT_XML
182     })
183     public Response readData(@Encoded @PathParam("identifier") final String identifier,
184             @Context final UriInfo uriInfo) {
185         final ReadDataParams readParams = QueryParams.newReadDataParams(uriInfo);
186
187         final EffectiveModelContext schemaContextRef = databindProvider.currentContext().modelContext();
188         // FIXME: go through
189         final InstanceIdentifierContext instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
190                 identifier, schemaContextRef, mountPointService);
191         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
192
193         // FIXME: this looks quite crazy, why do we even have it?
194         if (mountPoint == null && identifier != null && identifier.contains(STREAMS_PATH)
195             && !identifier.contains(STREAM_PATH_PART)) {
196             createAllYangNotificationStreams(schemaContextRef, uriInfo);
197         }
198
199         final QueryParameters queryParams = QueryParams.newQueryParameters(readParams, instanceIdentifier);
200         final List<YangInstanceIdentifier> fieldPaths = queryParams.fieldPaths();
201         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
202         final NormalizedNode node;
203         if (fieldPaths != null && !fieldPaths.isEmpty()) {
204             node = ReadDataTransactionUtil.readData(readParams.content(), instanceIdentifier.getInstanceIdentifier(),
205                     strategy, readParams.withDefaults(), schemaContextRef, fieldPaths);
206         } else {
207             node = ReadDataTransactionUtil.readData(readParams.content(), instanceIdentifier.getInstanceIdentifier(),
208                     strategy, readParams.withDefaults(), schemaContextRef);
209         }
210
211         // FIXME: this is utter craziness, refactor it properly!
212         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
213                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
214             final String value = (String) node.body();
215             final String streamName = value.substring(value.indexOf(NOTIFICATION_STREAM + '/'));
216             delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
217         }
218         if (node == null) {
219             throw new RestconfDocumentedException(
220                     "Request could not be completed because the relevant data model content does not exist",
221                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
222         }
223
224         return switch (readParams.content()) {
225             case ALL, CONFIG -> {
226                 final QName type = node.name().getNodeType();
227                 yield Response.status(Status.OK)
228                     .entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, queryParams))
229                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null) + "-"
230                         + type.getLocalName() + '"')
231                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
232                     .build();
233             }
234             case NONCONFIG -> Response.status(Status.OK)
235                 .entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, queryParams))
236                 .build();
237         };
238     }
239
240     private void createAllYangNotificationStreams(final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
241         final var transaction = dataBroker.newWriteOnlyTransaction();
242
243         for (var module : schemaContext.getModuleStatements().values()) {
244             final var moduleName = module.argument().getLocalName();
245             // Note: this handles only RFC6020 notifications
246             module.streamEffectiveSubstatements(NotificationEffectiveStatement.class).forEach(notification -> {
247                 final var notifName = notification.argument();
248
249                 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
250                     createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.XML));
251                 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
252                     createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.JSON));
253             });
254         }
255
256         try {
257             transaction.commit().get();
258         } catch (final InterruptedException | ExecutionException e) {
259             throw new RestconfDocumentedException("Problem while putting data to DS.", e);
260         }
261     }
262
263     private static NotificationListenerAdapter createYangNotifiStream(final ListenersBroker listenersBroker,
264             final String moduleName, final QName notifName, final NotificationOutputType outputType) {
265         final var streamName = createNotificationStreamName(moduleName, notifName.getLocalName(), outputType);
266
267         final var existing = listenersBroker.notificationListenerFor(streamName);
268         return existing != null ? existing
269             : listenersBroker.registerNotificationListener(Absolute.of(notifName), streamName, outputType);
270     }
271
272     private static String createNotificationStreamName(final String moduleName, final String notifName,
273             final NotificationOutputType outputType) {
274         final var sb = new StringBuilder()
275             .append(RestconfStreamsConstants.NOTIFICATION_STREAM)
276             .append('/').append(moduleName).append(':').append(notifName);
277         if (outputType != NotificationOutputType.XML) {
278             sb.append('/').append(outputType.getName());
279         }
280         return sb.toString();
281     }
282
283     private void writeNotificationStreamToDatastore(final EffectiveModelContext schemaContext,
284             final UriInfo uriInfo, final DOMDataTreeWriteOperations tx, final NotificationListenerAdapter listener) {
285         final URI uri = streamUtils.prepareUriByStreamName(uriInfo, listener.getStreamName());
286         final MapEntryNode mapToStreams = RestconfStateStreams.notificationStreamEntry(schemaContext,
287                 listener.getSchemaPath().lastNodeIdentifier(), null, listener.getOutputType(), uri);
288
289         tx.merge(LogicalDatastoreType.OPERATIONAL,
290             RestconfStateStreams.restconfStateStreamPath(mapToStreams.name()), mapToStreams);
291     }
292
293     /**
294      * Replace the data store.
295      *
296      * @param uriInfo request URI information
297      * @param body data node for put to config DS
298      * @return {@link Response}
299      */
300     @PUT
301     @Path("/data")
302     @Consumes({
303         MediaTypes.APPLICATION_YANG_DATA_JSON,
304         MediaType.APPLICATION_JSON,
305     })
306     public Response putDataJSON(@Context final UriInfo uriInfo, final InputStream body) {
307         try (var jsonBody = new JsonResourceBody(body)) {
308             return putData(null, uriInfo, jsonBody);
309         }
310     }
311
312     /**
313      * Create or replace the target data resource.
314      *
315      * @param identifier path to target
316      * @param uriInfo request URI information
317      * @param body data node for put to config DS
318      * @return {@link Response}
319      */
320     @PUT
321     @Path("/data/{identifier:.+}")
322     @Consumes({
323         MediaTypes.APPLICATION_YANG_DATA_JSON,
324         MediaType.APPLICATION_JSON,
325     })
326     public Response putDataJSON(@Encoded @PathParam("identifier") final String identifier,
327             @Context final UriInfo uriInfo, final InputStream body) {
328         try (var jsonBody = new JsonResourceBody(body)) {
329             return putData(identifier, uriInfo, jsonBody);
330         }
331     }
332
333     /**
334      * Replace the data store.
335      *
336      * @param uriInfo request URI information
337      * @param body data node for put to config DS
338      * @return {@link Response}
339      */
340     @PUT
341     @Path("/data")
342     @Consumes({
343         MediaTypes.APPLICATION_YANG_DATA_XML,
344         MediaType.APPLICATION_XML,
345         MediaType.TEXT_XML
346     })
347     public Response putDataXML(@Context final UriInfo uriInfo, final InputStream body) {
348         try (var xmlBody = new XmlResourceBody(body)) {
349             return putData(null, uriInfo, xmlBody);
350         }
351     }
352
353     /**
354      * Create or replace the target data resource.
355      *
356      * @param identifier path to target
357      * @param uriInfo request URI information
358      * @param body data node for put to config DS
359      * @return {@link Response}
360      */
361     @PUT
362     @Path("/data/{identifier:.+}")
363     @Consumes({
364         MediaTypes.APPLICATION_YANG_DATA_XML,
365         MediaType.APPLICATION_XML,
366         MediaType.TEXT_XML
367     })
368     public Response putDataXML(@Encoded @PathParam("identifier") final String identifier,
369             @Context final UriInfo uriInfo, final InputStream body) {
370         try (var xmlBody = new XmlResourceBody(body)) {
371             return putData(identifier, uriInfo, xmlBody);
372         }
373     }
374
375     private Response putData(final @Nullable String identifier, final UriInfo uriInfo, final ResourceBody body) {
376         final var params = QueryParams.newWriteDataParams(uriInfo);
377         final var req = bindResourceRequest(identifier, body);
378
379         return switch (
380             PutDataTransactionUtil.putData(req.path(), req.data(), req.modelContext(), req.strategy(), params)) {
381             // Note: no Location header, as it matches the request path
382             case CREATED -> Response.status(Status.CREATED).build();
383             case REPLACED -> Response.noContent().build();
384         };
385     }
386
387     /**
388      * Create a top-level data resource.
389      *
390      * @param body data node for put to config DS
391      * @param uriInfo URI info
392      * @return {@link Response}
393      */
394     @POST
395     @Path("/data/{identifier:.+}")
396     @Consumes({
397         MediaTypes.APPLICATION_YANG_DATA_JSON,
398         MediaType.APPLICATION_JSON,
399     })
400     public Response postDataJSON(final InputStream body, @Context final UriInfo uriInfo) {
401         try (var jsonBody = new JsonChildBody(body)) {
402             return postData(jsonBody, uriInfo);
403         }
404     }
405
406     /**
407      * Create a data resource in target.
408      *
409      * @param identifier path to target
410      * @param body data node for put to config DS
411      * @param uriInfo URI info
412      * @return {@link Response}
413      */
414     @POST
415     @Path("/data/{identifier:.+}")
416     @Consumes({
417         MediaTypes.APPLICATION_YANG_DATA_JSON,
418         MediaType.APPLICATION_JSON,
419     })
420     public Response postDataJSON(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
421             @Context final UriInfo uriInfo) {
422         final var instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier,
423             databindProvider.currentContext().modelContext(), mountPointService);
424         if (instanceIdentifier.getSchemaNode() instanceof ActionDefinition) {
425             try (var jsonBody = new JsonOperationInputBody(body)) {
426                 return invokeAction(instanceIdentifier, jsonBody);
427             }
428         }
429
430         try (var jsonBody = new JsonChildBody(body)) {
431             return postData(instanceIdentifier, jsonBody, uriInfo);
432         }
433     }
434
435     /**
436      * Create a top-level data resource.
437      *
438      * @param body data node for put to config DS
439      * @param uriInfo URI info
440      * @return {@link Response}
441      */
442     @POST
443     @Path("/data")
444     @Consumes({
445         MediaTypes.APPLICATION_YANG_DATA_XML,
446         MediaType.APPLICATION_XML,
447         MediaType.TEXT_XML
448     })
449     public Response postDataXML(final InputStream body, @Context final UriInfo uriInfo) {
450         try (var xmlBody = new XmlChildBody(body)) {
451             return postData(xmlBody, uriInfo);
452         }
453     }
454
455     /**
456      * Create a data resource in target.
457      *
458      * @param identifier path to target
459      * @param body data node for put to config DS
460      * @param uriInfo URI info
461      * @return {@link Response}
462      */
463     @POST
464     @Path("/data/{identifier:.+}")
465     @Consumes({
466         MediaTypes.APPLICATION_YANG_DATA_XML,
467         MediaType.APPLICATION_XML,
468         MediaType.TEXT_XML
469     })
470     public Response postDataXML(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
471             @Context final UriInfo uriInfo) {
472         final var instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier,
473             databindProvider.currentContext().modelContext(), mountPointService);
474         if (instanceIdentifier.getSchemaNode() instanceof ActionDefinition) {
475             try (var xmlBody = new XmlOperationInputBody(body)) {
476                 return invokeAction(instanceIdentifier, xmlBody);
477             }
478         }
479
480         try (var xmlBody = new XmlChildBody(body)) {
481             return postData(instanceIdentifier, xmlBody, uriInfo);
482         }
483     }
484
485     private Response postData(final ChildBody body, final UriInfo uriInfo) {
486         return postData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()), body,
487             uriInfo);
488     }
489
490     private Response postData(final InstanceIdentifierContext iid, final ChildBody body, final UriInfo uriInfo) {
491         final var params = QueryParams.newWriteDataParams(uriInfo);
492         final var strategy = getRestconfStrategy(iid.getMountPoint());
493         final var context = iid.getSchemaContext();
494         var path = iid.getInstanceIdentifier();
495         final var payload = body.toPayload(path, iid.inference());
496         final var data = payload.body();
497
498         for (var arg : payload.prefix()) {
499             path = path.node(arg);
500         }
501
502         PostDataTransactionUtil.postData(path, data, strategy, context, params);
503         return Response.created(resolveLocation(uriInfo, path, context, data)).build();
504     }
505
506     /**
507      * Get location from {@link YangInstanceIdentifier} and {@link UriInfo}.
508      *
509      * @param uriInfo       uri info
510      * @param initialPath   data path
511      * @param schemaContext reference to {@link SchemaContext}
512      * @return {@link URI}
513      */
514     private static URI resolveLocation(final UriInfo uriInfo, final YangInstanceIdentifier initialPath,
515                                        final EffectiveModelContext schemaContext, final NormalizedNode data) {
516         YangInstanceIdentifier path = initialPath;
517         if (data instanceof MapNode mapData) {
518             final var children = mapData.body();
519             if (!children.isEmpty()) {
520                 path = path.node(children.iterator().next().name());
521             }
522         }
523
524         return uriInfo.getBaseUriBuilder().path("data").path(IdentifierCodec.serialize(path, schemaContext)).build();
525     }
526
527     /**
528      * Delete the target data resource.
529      *
530      * @param identifier path to target
531      * @param ar {@link AsyncResponse} which needs to be completed
532      */
533     @DELETE
534     @Path("/data/{identifier:.+}")
535     public void deleteData(@Encoded @PathParam("identifier") final String identifier,
536             @Suspended final AsyncResponse ar) {
537         final var instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier,
538             databindProvider.currentContext().modelContext(), mountPointService);
539         final var strategy = getRestconfStrategy(instanceIdentifier.getMountPoint());
540
541         Futures.addCallback(strategy.delete(instanceIdentifier.getInstanceIdentifier()), new FutureCallback<>() {
542             @Override
543             public void onSuccess(final Empty result) {
544                 ar.resume(Response.noContent().build());
545             }
546
547             @Override
548             public void onFailure(final Throwable failure) {
549                 ar.resume(failure);
550             }
551         }, MoreExecutors.directExecutor());
552     }
553
554     /**
555      * Partially modify the target data store, as defined in
556      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
557      *
558      * @param body data node for put to config DS
559      * @param ar {@link AsyncResponse} which needs to be completed
560      */
561     @PATCH
562     @Path("/data")
563     @Consumes({
564         MediaTypes.APPLICATION_YANG_DATA_XML,
565         MediaType.APPLICATION_XML,
566         MediaType.TEXT_XML
567     })
568     public void plainPatchDataXML(final InputStream body, @Suspended final AsyncResponse ar) {
569         try (var xmlBody = new XmlResourceBody(body)) {
570             plainPatchData(null, xmlBody, ar);
571         }
572     }
573
574     /**
575      * Partially modify the target data resource, as defined in
576      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
577      *
578      * @param identifier path to target
579      * @param body data node for put to config DS
580      * @param ar {@link AsyncResponse} which needs to be completed
581      */
582     @PATCH
583     @Path("/data/{identifier:.+}")
584     @Consumes({
585         MediaTypes.APPLICATION_YANG_DATA_XML,
586         MediaType.APPLICATION_XML,
587         MediaType.TEXT_XML
588     })
589     public void plainPatchDataXML(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
590             @Suspended final AsyncResponse ar) {
591         try (var xmlBody = new XmlResourceBody(body)) {
592             plainPatchData(identifier, xmlBody, ar);
593         }
594     }
595
596     /**
597      * Partially modify the target data store, as defined in
598      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
599      *
600      * @param body data node for put to config DS
601      * @param ar {@link AsyncResponse} which needs to be completed
602      */
603     @PATCH
604     @Path("/data")
605     @Consumes({
606         MediaTypes.APPLICATION_YANG_DATA_JSON,
607         MediaType.APPLICATION_JSON,
608     })
609     public void plainPatchDataJSON(final InputStream body, @Suspended final AsyncResponse ar) {
610         try (var jsonBody = new JsonResourceBody(body)) {
611             plainPatchData(null, jsonBody, ar);
612         }
613     }
614
615     /**
616      * Partially modify the target data resource, as defined in
617      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
618      *
619      * @param identifier path to target
620      * @param body data node for put to config DS
621      * @param ar {@link AsyncResponse} which needs to be completed
622      */
623     @PATCH
624     @Path("/data/{identifier:.+}")
625     @Consumes({
626         MediaTypes.APPLICATION_YANG_DATA_JSON,
627         MediaType.APPLICATION_JSON,
628     })
629     public void plainPatchDataJSON(@Encoded @PathParam("identifier") final String identifier, final InputStream body,
630             @Suspended final AsyncResponse ar) {
631         try (var jsonBody = new JsonResourceBody(body)) {
632             plainPatchData(identifier, jsonBody, ar);
633         }
634     }
635
636     /**
637      * Partially modify the target data resource, as defined in
638      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040, section 4.6.1</a>.
639      *
640      * @param identifier path to target
641      * @param body data node for put to config DS
642      * @param ar {@link AsyncResponse} which needs to be completed
643      */
644     private void plainPatchData(final @Nullable String identifier, final ResourceBody body, final AsyncResponse ar) {
645         final var req = bindResourceRequest(identifier, body);
646         final var future = req.strategy().merge(req.path(), req.data(), req.modelContext());
647
648         Futures.addCallback(future, new FutureCallback<>() {
649             @Override
650             public void onSuccess(final Empty result) {
651                 ar.resume(Response.ok().build());
652             }
653
654             @Override
655             public void onFailure(final Throwable failure) {
656                 ar.resume(failure);
657             }
658         }, MoreExecutors.directExecutor());
659     }
660
661     private @NonNull ResourceRequest bindResourceRequest(final @Nullable String identifier, final ResourceBody body) {
662         final var dataBind = databindProvider.currentContext();
663         final var context = ParserIdentifier.toInstanceIdentifier(identifier, dataBind.modelContext(),
664             mountPointService);
665         final var inference = context.inference();
666         final var path = context.getInstanceIdentifier();
667         final var data = body.toNormalizedNode(path, inference, context.getSchemaNode());
668
669         return new ResourceRequest(getRestconfStrategy(context.getMountPoint()), inference.getEffectiveModelContext(),
670             path, data);
671     }
672
673     /**
674      * Ordered list of edits that are applied to the target datastore by the server, as defined in
675      * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
676      *
677      * @param identifier path to target
678      * @param body YANG Patch body
679      * @return {@link PatchStatusContext}
680      */
681     @PATCH
682     @Path("/data/{identifier:.+}")
683     @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
684     @Produces({
685         MediaTypes.APPLICATION_YANG_DATA_JSON,
686         MediaTypes.APPLICATION_YANG_DATA_XML
687     })
688     public PatchStatusContext yangPatchDataXML(@Encoded @PathParam("identifier") final String identifier,
689             final InputStream body) {
690         try (var xmlBody = new XmlPatchBody(body)) {
691             return yangPatchData(identifier, xmlBody);
692         }
693     }
694
695     /**
696      * Ordered list of edits that are applied to the datastore by the server, as defined in
697      * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
698      *
699      * @param body YANG Patch body
700      * @return {@link PatchStatusContext}
701      */
702     @PATCH
703     @Path("/data")
704     @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
705     @Produces({
706         MediaTypes.APPLICATION_YANG_DATA_JSON,
707         MediaTypes.APPLICATION_YANG_DATA_XML
708     })
709     public PatchStatusContext yangPatchDataXML(final InputStream body) {
710         try (var xmlBody = new XmlPatchBody(body)) {
711             return yangPatchData(xmlBody);
712         }
713     }
714
715     /**
716      * Ordered list of edits that are applied to the target datastore by the server, as defined in
717      * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
718      *
719      * @param identifier path to target
720      * @param body YANG Patch body
721      * @return {@link PatchStatusContext}
722      */
723     @PATCH
724     @Path("/data/{identifier:.+}")
725     @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
726     @Produces({
727         MediaTypes.APPLICATION_YANG_DATA_JSON,
728         MediaTypes.APPLICATION_YANG_DATA_XML
729     })
730     public PatchStatusContext yangPatchDataJSON(@Encoded @PathParam("identifier") final String identifier,
731             final InputStream body) {
732         try (var jsonBody = new JsonPatchBody(body)) {
733             return yangPatchData(identifier, jsonBody);
734         }
735     }
736
737     /**
738      * Ordered list of edits that are applied to the datastore by the server, as defined in
739      * <a href="https://www.rfc-editor.org/rfc/rfc8072#section-2">RFC8072, section 2</a>.
740      *
741      * @param body YANG Patch body
742      * @return {@link PatchStatusContext}
743      */
744     @PATCH
745     @Path("/data")
746     @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
747     @Produces({
748         MediaTypes.APPLICATION_YANG_DATA_JSON,
749         MediaTypes.APPLICATION_YANG_DATA_XML
750     })
751     public PatchStatusContext yangPatchDataJSON(final InputStream body) {
752         try (var jsonBody = new JsonPatchBody(body)) {
753             return yangPatchData(jsonBody);
754         }
755     }
756
757     private PatchStatusContext yangPatchData(final @NonNull PatchBody body) {
758         return yangPatchData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()),
759             body);
760     }
761
762     private PatchStatusContext yangPatchData(final String identifier, final @NonNull PatchBody body) {
763         return yangPatchData(ParserIdentifier.toInstanceIdentifier(identifier,
764                 databindProvider.currentContext().modelContext(), mountPointService), body);
765     }
766
767     private PatchStatusContext yangPatchData(final @NonNull InstanceIdentifierContext targetResource,
768             final @NonNull PatchBody body) {
769         try {
770             return yangPatchData(targetResource, body.toPatchContext(targetResource));
771         } catch (IOException e) {
772             LOG.debug("Error parsing YANG Patch input", e);
773             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
774                     ErrorTag.MALFORMED_MESSAGE, e);
775         }
776     }
777
778     @VisibleForTesting
779     PatchStatusContext yangPatchData(final InstanceIdentifierContext targetResource, final PatchContext context) {
780         return PatchDataTransactionUtil.patchData(context, getRestconfStrategy(targetResource.getMountPoint()),
781             targetResource.getSchemaContext());
782     }
783
784     @VisibleForTesting
785     RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
786         if (mountPoint == null) {
787             return restconfStrategy;
788         }
789
790         return RestconfStrategy.forMountPoint(mountPoint).orElseThrow(() -> {
791             LOG.warn("Mount point {} does not expose a suitable access interface", mountPoint.getIdentifier());
792             return new RestconfDocumentedException("Could not find a supported access interface in mount point "
793                 + mountPoint.getIdentifier());
794         });
795     }
796
797     /**
798      * Invoke Action operation.
799      *
800      * @param payload {@link NormalizedNodePayload} - the body of the operation
801      * @return {@link NormalizedNodePayload} wrapped in {@link Response}
802      */
803     private Response invokeAction(final InstanceIdentifierContext context, final OperationInputBody body) {
804         final var yangIIdContext = context.getInstanceIdentifier();
805         final ContainerNode input;
806         try {
807             input = body.toContainerNode(context.inference());
808         } catch (IOException e) {
809             LOG.debug("Error reading input", e);
810             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
811                     ErrorTag.MALFORMED_MESSAGE, e);
812         }
813
814         final var mountPoint = context.getMountPoint();
815         final var schemaPath = context.inference().toSchemaInferenceStack().toSchemaNodeIdentifier();
816         final var response = mountPoint != null ? invokeAction(input, schemaPath, yangIIdContext, mountPoint)
817             : invokeAction(input, schemaPath, yangIIdContext, actionService);
818         final var result = checkActionResponse(response);
819
820         final var resultData = result != null ? result.getOutput().orElse(null) : null;
821         if (resultData != null && resultData.isEmpty()) {
822             return Response.status(Status.NO_CONTENT).build();
823         }
824         return Response.status(Status.OK).entity(NormalizedNodePayload.ofNullable(context, resultData)).build();
825     }
826
827     /**
828      * Invoking Action via mount point.
829      *
830      * @param mountPoint mount point
831      * @param data input data
832      * @param schemaPath schema path of data
833      * @return {@link DOMActionResult}
834      */
835     private static DOMActionResult invokeAction(final ContainerNode data,
836             final Absolute schemaPath, final YangInstanceIdentifier yangIId, final DOMMountPoint mountPoint) {
837         return invokeAction(data, schemaPath, yangIId, mountPoint.getService(DOMActionService.class)
838             .orElseThrow(() -> new RestconfDocumentedException("DomAction service is missing.")));
839     }
840
841     /**
842      * Invoke Action via ActionServiceHandler.
843      *
844      * @param data input data
845      * @param yangIId invocation context
846      * @param schemaPath schema path of data
847      * @param actionService action service to invoke action
848      * @return {@link DOMActionResult}
849      */
850     // FIXME: NETCONF-718: we should be returning a future here
851     private static DOMActionResult invokeAction(final ContainerNode data, final Absolute schemaPath,
852             final YangInstanceIdentifier yangIId, final DOMActionService actionService) {
853         return RestconfInvokeOperationsServiceImpl.checkedGet(Futures.catching(actionService.invokeAction(
854             schemaPath, new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, yangIId.getParent()), data),
855             DOMActionException.class,
856             cause -> new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
857                 ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))),
858             MoreExecutors.directExecutor()));
859     }
860
861     /**
862      * Check the validity of the result.
863      *
864      * @param response response of Action
865      * @return {@link DOMActionResult} result
866      */
867     private static DOMActionResult checkActionResponse(final DOMActionResult response) {
868         if (response == null) {
869             return null;
870         }
871
872         try {
873             if (response.getErrors().isEmpty()) {
874                 return response;
875             }
876             LOG.debug("InvokeAction Error Message {}", response.getErrors());
877             throw new RestconfDocumentedException("InvokeAction Error Message ", null, response.getErrors());
878         } catch (final CancellationException e) {
879             final String errMsg = "The Action Operation was cancelled while executing.";
880             LOG.debug("Cancel Execution: {}", errMsg, e);
881             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
882         }
883     }
884 }