Introduce UriInfoSupport
[netconf.git] / restconf / restconf-nb-rfc8040 / 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.collect.ImmutableList;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.net.URI;
23 import java.time.Clock;
24 import java.time.LocalDateTime;
25 import java.time.format.DateTimeFormatter;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.concurrent.CancellationException;
32 import java.util.concurrent.ExecutionException;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.Response.Status;
36 import javax.ws.rs.core.UriInfo;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
39 import org.opendaylight.mdsal.dom.api.DOMActionException;
40 import org.opendaylight.mdsal.dom.api.DOMActionResult;
41 import org.opendaylight.mdsal.dom.api.DOMActionService;
42 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
46 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
47 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
48 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
49 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
50 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
51 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
52 import org.opendaylight.restconf.common.patch.PatchContext;
53 import org.opendaylight.restconf.common.patch.PatchStatusContext;
54 import org.opendaylight.restconf.nb.rfc8040.InsertParameter;
55 import org.opendaylight.restconf.nb.rfc8040.PointParameter;
56 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
57 import org.opendaylight.restconf.nb.rfc8040.databind.jaxrs.UriInfoSupport;
58 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
59 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
60 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
61 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
62 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
63 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
64 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
65 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
66 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
67 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil;
68 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
69 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
70 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
71 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
72 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
73 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
74 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
75 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
76 import org.opendaylight.yangtools.concepts.Immutable;
77 import org.opendaylight.yangtools.yang.common.ErrorTag;
78 import org.opendaylight.yangtools.yang.common.ErrorType;
79 import org.opendaylight.yangtools.yang.common.QName;
80 import org.opendaylight.yangtools.yang.common.Revision;
81 import org.opendaylight.yangtools.yang.common.RpcError;
82 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
89 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
90 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98
99 /**
100  * Implementation of {@link RestconfDataService}.
101  */
102 @Path("/")
103 public class RestconfDataServiceImpl implements RestconfDataService {
104     // FIXME: we should be able to interpret 'point' and refactor this class into a behavior
105     private static final class QueryParams implements Immutable {
106         final @Nullable PointParameter point;
107         final @Nullable InsertParameter insert;
108
109         QueryParams(final @Nullable InsertParameter insert, final @Nullable PointParameter point) {
110             this.insert = insert;
111             this.point = point;
112         }
113     }
114
115     private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
116     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
117     private static final QName NETCONF_BASE_QNAME = SchemaContext.NAME;
118
119     private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
120     private final SchemaContextHandler schemaContextHandler;
121     private final MdsalRestconfStrategy restconfStrategy;
122     private final DOMMountPointService mountPointService;
123     private final SubscribeToStreamUtil streamUtils;
124     private final DOMActionService actionService;
125     private final DOMDataBroker dataBroker;
126
127     public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
128             final DOMDataBroker dataBroker, final DOMMountPointService  mountPointService,
129             final RestconfStreamsSubscriptionService delegRestconfSubscrService,
130             final DOMActionService actionService, final Configuration configuration) {
131         this.schemaContextHandler = requireNonNull(schemaContextHandler);
132         this.dataBroker = requireNonNull(dataBroker);
133         restconfStrategy = new MdsalRestconfStrategy(dataBroker);
134         this.mountPointService = requireNonNull(mountPointService);
135         this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
136         this.actionService = requireNonNull(actionService);
137         streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
138                 : SubscribeToStreamUtil.webSockets();
139     }
140
141     @Override
142     public Response readData(final UriInfo uriInfo) {
143         return readData(null, uriInfo);
144     }
145
146     @Override
147     public Response readData(final String identifier, final UriInfo uriInfo) {
148         final EffectiveModelContext schemaContextRef = schemaContextHandler.get();
149         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
150                 identifier, schemaContextRef, Optional.of(mountPointService));
151         final QueryParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
152
153         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
154
155         // FIXME: this looks quite crazy, why do we even have it?
156         if (mountPoint == null && identifier != null && identifier.contains(STREAMS_PATH)
157             && !identifier.contains(STREAM_PATH_PART)) {
158             createAllYangNotificationStreams(schemaContextRef, uriInfo);
159         }
160
161         final List<YangInstanceIdentifier> fieldPaths = parameters.getFieldPaths();
162         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
163         final NormalizedNode node;
164         if (fieldPaths != null && !fieldPaths.isEmpty()) {
165             node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
166                     strategy, parameters.getWithDefault(), schemaContextRef, fieldPaths);
167         } else {
168             node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
169                     strategy, parameters.getWithDefault(), schemaContextRef);
170         }
171
172         // FIXME: this is utter craziness, refactor it properly!
173         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
174                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
175             final String value = (String) node.body();
176             final String streamName = value.substring(value.indexOf(NOTIFICATION_STREAM + '/'));
177             delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
178         }
179         if (node == null) {
180             throw new RestconfDocumentedException(
181                     "Request could not be completed because the relevant data model content does not exist",
182                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
183         }
184
185         switch (parameters.getContent()) {
186             case ALL:
187             case CONFIG:
188                 final QName type = node.getIdentifier().getNodeType();
189                 return Response.status(Status.OK)
190                     .entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, parameters))
191                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
192                         + "-" + type.getLocalName() + '"')
193                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
194                     .build();
195             default:
196                 return Response.status(Status.OK)
197                     .entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, parameters))
198                     .build();
199         }
200     }
201
202     private void createAllYangNotificationStreams(final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
203         final DOMDataTreeWriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
204         for (final NotificationDefinition notificationDefinition : schemaContext.getNotifications()) {
205             writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
206                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
207                     NotificationOutputType.XML));
208             writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
209                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
210                     NotificationOutputType.JSON));
211         }
212         try {
213             transaction.commit().get();
214         } catch (final InterruptedException | ExecutionException e) {
215             throw new RestconfDocumentedException("Problem while putting data to DS.", e);
216         }
217     }
218
219     private void writeNotificationStreamToDatastore(final EffectiveModelContext schemaContext,
220             final UriInfo uriInfo, final DOMDataTreeWriteOperations tx, final NotificationListenerAdapter listener) {
221         final URI uri = streamUtils.prepareUriByStreamName(uriInfo, listener.getStreamName());
222         final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
223                 listener.getSchemaPath().lastNodeIdentifier(), schemaContext.getNotifications(), null,
224                 listener.getOutputType(), uri);
225
226         tx.merge(LogicalDatastoreType.OPERATIONAL,
227             Rfc8040.restconfStateStreamPath(mapToStreams.getIdentifier()), mapToStreams);
228     }
229
230     @Override
231     public Response putData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
232         requireNonNull(payload);
233
234         final QueryParams checkedParms = checkQueryParameters(uriInfo);
235
236         final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
237
238         validInputData(iid.getSchemaNode(), payload);
239         validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
240         validateListKeysEqualityInPayloadAndUri(payload);
241
242         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
243         final EffectiveModelContext ref = mountPoint == null
244                 ? schemaContextHandler.get() : modelContext(mountPoint);
245
246         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
247         return PutDataTransactionUtil.putData(payload, ref, strategy, checkedParms.insert, checkedParms.point);
248     }
249
250     private static QueryParams checkQueryParameters(final UriInfo uriInfo) {
251         InsertParameter insert = null;
252         PointParameter point = null;
253
254         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
255             final String uriName = entry.getKey();
256             final List<String> paramValues = entry.getValue();
257             if (uriName.equals(InsertParameter.uriName())) {
258                 final String str = UriInfoSupport.optionalParam(uriName, paramValues);
259                 if (str != null) {
260                     insert = InsertParameter.forUriValue(str);
261                     if (insert == null) {
262                         throw new RestconfDocumentedException("Unrecognized insert parameter value '" + str + "'",
263                             ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
264                     }
265                 }
266             } else if (PointParameter.uriName().equals(uriName)) {
267                 final String str = UriInfoSupport.optionalParam(uriName, paramValues);
268                 if (str != null) {
269                     point = PointParameter.forUriValue(str);
270                 }
271             } else {
272                 throw new RestconfDocumentedException("Bad parameter for post: " + uriName,
273                     ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
274             }
275         }
276
277         // https://datatracker.ietf.org/doc/html/rfc8040#section-4.8.5:
278         //        If the values "before" or "after" are used, then a "point" query
279         //        parameter for the "insert" query parameter MUST also be present, or a
280         //        "400 Bad Request" status-line is returned.
281         if ((insert == InsertParameter.BEFORE || insert == InsertParameter.AFTER) && point == null) {
282             throw new RestconfDocumentedException(
283                 "Insert parameter " + insert.uriValue() + " cannot be used without a Point parameter.",
284                 ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
285         }
286         // https://datatracker.ietf.org/doc/html/rfc8040#section-4.8.6:
287         //        If the "insert" query parameter is not present or has a value other
288         //        than "before" or "after", then a "400 Bad Request" status-line is
289         //        returned.
290         if (point != null && insert != InsertParameter.BEFORE && insert != InsertParameter.AFTER) {
291             throw new RestconfDocumentedException(
292                 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
293                 ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
294         }
295
296         return new QueryParams(insert, point);
297     }
298
299     @Override
300     public Response postData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
301         return postData(payload, uriInfo);
302     }
303
304     @Override
305     public Response postData(final NormalizedNodePayload payload, final UriInfo uriInfo) {
306         requireNonNull(payload);
307         if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
308             return invokeAction(payload);
309         }
310
311         final QueryParams checkedParms = checkQueryParameters(uriInfo);
312         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
313         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
314         return PostDataTransactionUtil.postData(uriInfo, payload, strategy,
315                 getSchemaContext(mountPoint), checkedParms.insert, checkedParms.point);
316     }
317
318     @Override
319     public Response deleteData(final String identifier) {
320         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
321                 identifier, schemaContextHandler.get(), Optional.of(mountPointService));
322
323         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
324         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
325         return DeleteDataTransactionUtil.deleteData(strategy, instanceIdentifier.getInstanceIdentifier());
326     }
327
328     @Override
329     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
330         return patchData(context, uriInfo);
331     }
332
333     @Override
334     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
335         final DOMMountPoint mountPoint = RestconfDocumentedException.throwIfNull(context,
336             ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "No patch documented provided")
337             .getInstanceIdentifierContext().getMountPoint();
338         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
339         return PatchDataTransactionUtil.patchData(context, strategy, getSchemaContext(mountPoint));
340     }
341
342     @Override
343     public Response patchData(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo) {
344         requireNonNull(payload);
345
346         final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
347         validInputData(iid.getSchemaNode(), payload);
348         validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
349         validateListKeysEqualityInPayloadAndUri(payload);
350
351         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
352         final EffectiveModelContext ref = mountPoint == null
353                 ? schemaContextHandler.get() : modelContext(mountPoint);
354         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
355
356         return PlainPatchDataTransactionUtil.patchData(payload, strategy, ref);
357     }
358
359     private EffectiveModelContext getSchemaContext(final DOMMountPoint mountPoint) {
360         return mountPoint == null ? schemaContextHandler.get() : modelContext(mountPoint);
361     }
362
363     // FIXME: why is this synchronized?
364     public synchronized RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
365         if (mountPoint == null) {
366             return restconfStrategy;
367         }
368
369         return RestconfStrategy.forMountPoint(mountPoint).orElseThrow(() -> {
370             LOG.warn("Mount point {} does not expose a suitable access interface", mountPoint.getIdentifier());
371             return new RestconfDocumentedException("Could not find a supported access interface in mount point "
372                 + mountPoint.getIdentifier());
373         });
374     }
375
376     /**
377      * Invoke Action operation.
378      *
379      * @param payload {@link NormalizedNodePayload} - the body of the operation
380      * @return {@link NormalizedNodePayload} wrapped in {@link Response}
381      */
382     public Response invokeAction(final NormalizedNodePayload payload) {
383         final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
384         final DOMMountPoint mountPoint = context.getMountPoint();
385         final Absolute schemaPath = Absolute.of(ImmutableList.copyOf(context.getSchemaNode().getPath()
386             .getPathFromRoot()));
387         final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
388         final NormalizedNode data = payload.getData();
389
390         if (yangIIdContext.isEmpty() && !NETCONF_BASE_QNAME.equals(data.getIdentifier().getNodeType())) {
391             throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
392                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
393         }
394
395         final DOMActionResult response;
396         final EffectiveModelContext schemaContextRef;
397         if (mountPoint != null) {
398             response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, mountPoint);
399             schemaContextRef = modelContext(mountPoint);
400         } else {
401             response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, actionService);
402             schemaContextRef = schemaContextHandler.get();
403         }
404         final DOMActionResult result = checkActionResponse(response);
405
406         ActionDefinition resultNodeSchema = null;
407         ContainerNode resultData = null;
408         if (result != null) {
409             final Optional<ContainerNode> optOutput = result.getOutput();
410             if (optOutput.isPresent()) {
411                 resultData = optOutput.get();
412                 resultNodeSchema = (ActionDefinition) context.getSchemaNode();
413             }
414         }
415
416         if (resultData != null && resultData.isEmpty()) {
417             return Response.status(Status.NO_CONTENT).build();
418         }
419
420         return Response.status(Status.OK)
421             .entity(NormalizedNodePayload.ofNullable(
422                 new InstanceIdentifierContext<>(yangIIdContext, resultNodeSchema, mountPoint, schemaContextRef),
423                 resultData))
424             .build();
425     }
426
427
428     /**
429      * Invoking Action via mount point.
430      *
431      * @param mountPoint mount point
432      * @param data input data
433      * @param schemaPath schema path of data
434      * @return {@link DOMActionResult}
435      */
436     private static DOMActionResult invokeAction(final ContainerNode data,
437             final Absolute schemaPath, final YangInstanceIdentifier yangIId, final DOMMountPoint mountPoint) {
438         return invokeAction(data, schemaPath, yangIId, mountPoint.getService(DOMActionService.class)
439             .orElseThrow(() -> new RestconfDocumentedException("DomAction service is missing.")));
440     }
441
442     /**
443      * Invoke Action via ActionServiceHandler.
444      *
445      * @param data input data
446      * @param yangIId invocation context
447      * @param schemaPath schema path of data
448      * @param actionService action service to invoke action
449      * @return {@link DOMActionResult}
450      */
451     // FIXME: NETCONF-718: we should be returning a future here
452     private static DOMActionResult invokeAction(final ContainerNode data, final Absolute schemaPath,
453             final YangInstanceIdentifier yangIId, final DOMActionService actionService) {
454         return RestconfInvokeOperationsServiceImpl.checkedGet(Futures.catching(actionService.invokeAction(
455             schemaPath, new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, yangIId.getParent()), data),
456             DOMActionException.class,
457             cause -> new SimpleDOMActionResult(ImmutableList.of(RpcResultBuilder.newError(
458                 RpcError.ErrorType.RPC, "operation-failed", cause.getMessage()))),
459             MoreExecutors.directExecutor()));
460     }
461
462     /**
463      * Check the validity of the result.
464      *
465      * @param response response of Action
466      * @return {@link DOMActionResult} result
467      */
468     private static DOMActionResult checkActionResponse(final DOMActionResult response) {
469         if (response == null) {
470             return null;
471         }
472
473         try {
474             if (response.getErrors().isEmpty()) {
475                 return response;
476             }
477             LOG.debug("InvokeAction Error Message {}", response.getErrors());
478             throw new RestconfDocumentedException("InvokeAction Error Message ", null, response.getErrors());
479         } catch (final CancellationException e) {
480             final String errMsg = "The Action Operation was cancelled while executing.";
481             LOG.debug("Cancel Execution: {}", errMsg, e);
482             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
483         }
484     }
485
486     /**
487      * Valid input data with {@link SchemaNode}.
488      *
489      * @param schemaNode {@link SchemaNode}
490      * @param payload    input data
491      */
492     @VisibleForTesting
493     public static void validInputData(final SchemaNode schemaNode, final NormalizedNodePayload payload) {
494         if (schemaNode != null && payload.getData() == null) {
495             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
496         } else if (schemaNode == null && payload.getData() != null) {
497             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
498         }
499     }
500
501     /**
502      * Valid top level node name.
503      *
504      * @param path    path of node
505      * @param payload data
506      */
507     @VisibleForTesting
508     public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodePayload payload) {
509         final QName dataNodeType = payload.getData().getIdentifier().getNodeType();
510         if (path.isEmpty()) {
511             if (!NETCONF_BASE_QNAME.equals(dataNodeType)) {
512                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
513                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
514             }
515         } else {
516             final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
517             final String payloadName = dataNodeType.getLocalName();
518             if (!payloadName.equals(identifierName)) {
519                 throw new RestconfDocumentedException(
520                         "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
521                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
522             }
523         }
524     }
525
526
527     /**
528      * Validates whether keys in {@code payload} are equal to values of keys in
529      * {@code iiWithData} for list schema node.
530      *
531      * @throws RestconfDocumentedException if key values or key count in payload and URI isn't equal
532      */
533     @VisibleForTesting
534     public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodePayload payload) {
535         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
536         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
537         final SchemaNode schemaNode = iiWithData.getSchemaNode();
538         final NormalizedNode data = payload.getData();
539         if (schemaNode instanceof ListSchemaNode) {
540             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
541             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
542                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
543                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
544             }
545         }
546     }
547
548     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
549             final List<QName> keyDefinitions) {
550         final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
551         for (final QName keyDefinition : keyDefinitions) {
552             final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
553                     mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
554                     "Missing key %s in URI.", keyDefinition);
555
556             final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
557
558             if (!uriKeyValue.equals(dataKeyValue)) {
559                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
560                         + "' specified in the URI doesn't match the value '" + dataKeyValue
561                         + "' specified in the message body. ";
562                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
563             }
564         }
565     }
566
567     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
568         return mountPoint.getService(DOMSchemaService.class)
569             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
570             .orElse(null);
571     }
572 }