2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
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;
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;
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;
117 * The "{+restconf}/data" subtree represents the datastore resource type, which is a collection of configuration data
118 * and state data nodes.
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");
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();
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();
149 * Get target data resource from data root.
151 * @param uriInfo URI info
152 * @return {@link NormalizedNodePayload}
157 MediaTypes.APPLICATION_YANG_DATA_JSON,
158 MediaTypes.APPLICATION_YANG_DATA_XML,
159 MediaType.APPLICATION_JSON,
160 MediaType.APPLICATION_XML,
163 public Response readData(@Context final UriInfo uriInfo) {
164 return readData(null, uriInfo);
168 * Get target data resource.
170 * @param identifier path to target
171 * @param uriInfo URI info
172 * @return {@link NormalizedNodePayload}
175 @Path("/data/{identifier:.+}")
177 MediaTypes.APPLICATION_YANG_DATA_JSON,
178 MediaTypes.APPLICATION_YANG_DATA_XML,
179 MediaType.APPLICATION_JSON,
180 MediaType.APPLICATION_XML,
183 public Response readData(@Encoded @PathParam("identifier") final String identifier,
184 @Context final UriInfo uriInfo) {
185 final ReadDataParams readParams = QueryParams.newReadDataParams(uriInfo);
187 final EffectiveModelContext schemaContextRef = databindProvider.currentContext().modelContext();
189 final InstanceIdentifierContext instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
190 identifier, schemaContextRef, mountPointService);
191 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
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);
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);
207 node = ReadDataTransactionUtil.readData(readParams.content(), instanceIdentifier.getInstanceIdentifier(),
208 strategy, readParams.withDefaults(), schemaContextRef);
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);
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);
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())))
234 case NONCONFIG -> Response.status(Status.OK)
235 .entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, queryParams))
240 private void createAllYangNotificationStreams(final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
241 final var transaction = dataBroker.newWriteOnlyTransaction();
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();
249 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
250 createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.XML));
251 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
252 createYangNotifiStream(listenersBroker, moduleName, notifName, NotificationOutputType.JSON));
257 transaction.commit().get();
258 } catch (final InterruptedException | ExecutionException e) {
259 throw new RestconfDocumentedException("Problem while putting data to DS.", e);
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);
267 final var existing = listenersBroker.notificationListenerFor(streamName);
268 return existing != null ? existing
269 : listenersBroker.registerNotificationListener(Absolute.of(notifName), streamName, outputType);
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());
280 return sb.toString();
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);
289 tx.merge(LogicalDatastoreType.OPERATIONAL,
290 RestconfStateStreams.restconfStateStreamPath(mapToStreams.name()), mapToStreams);
294 * Replace the data store.
296 * @param uriInfo request URI information
297 * @param body data node for put to config DS
298 * @return {@link Response}
303 MediaTypes.APPLICATION_YANG_DATA_JSON,
304 MediaType.APPLICATION_JSON,
306 public Response putDataJSON(@Context final UriInfo uriInfo, final InputStream body) {
307 try (var jsonBody = new JsonResourceBody(body)) {
308 return putData(null, uriInfo, jsonBody);
313 * Create or replace the target data resource.
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}
321 @Path("/data/{identifier:.+}")
323 MediaTypes.APPLICATION_YANG_DATA_JSON,
324 MediaType.APPLICATION_JSON,
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);
334 * Replace the data store.
336 * @param uriInfo request URI information
337 * @param body data node for put to config DS
338 * @return {@link Response}
343 MediaTypes.APPLICATION_YANG_DATA_XML,
344 MediaType.APPLICATION_XML,
347 public Response putDataXML(@Context final UriInfo uriInfo, final InputStream body) {
348 try (var xmlBody = new XmlResourceBody(body)) {
349 return putData(null, uriInfo, xmlBody);
354 * Create or replace the target data resource.
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}
362 @Path("/data/{identifier:.+}")
364 MediaTypes.APPLICATION_YANG_DATA_XML,
365 MediaType.APPLICATION_XML,
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);
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);
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();
388 * Create a top-level data resource.
390 * @param body data node for put to config DS
391 * @param uriInfo URI info
392 * @return {@link Response}
395 @Path("/data/{identifier:.+}")
397 MediaTypes.APPLICATION_YANG_DATA_JSON,
398 MediaType.APPLICATION_JSON,
400 public Response postDataJSON(final InputStream body, @Context final UriInfo uriInfo) {
401 try (var jsonBody = new JsonChildBody(body)) {
402 return postData(jsonBody, uriInfo);
407 * Create a data resource in target.
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}
415 @Path("/data/{identifier:.+}")
417 MediaTypes.APPLICATION_YANG_DATA_JSON,
418 MediaType.APPLICATION_JSON,
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);
430 try (var jsonBody = new JsonChildBody(body)) {
431 return postData(instanceIdentifier, jsonBody, uriInfo);
436 * Create a top-level data resource.
438 * @param body data node for put to config DS
439 * @param uriInfo URI info
440 * @return {@link Response}
445 MediaTypes.APPLICATION_YANG_DATA_XML,
446 MediaType.APPLICATION_XML,
449 public Response postDataXML(final InputStream body, @Context final UriInfo uriInfo) {
450 try (var xmlBody = new XmlChildBody(body)) {
451 return postData(xmlBody, uriInfo);
456 * Create a data resource in target.
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}
464 @Path("/data/{identifier:.+}")
466 MediaTypes.APPLICATION_YANG_DATA_XML,
467 MediaType.APPLICATION_XML,
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);
480 try (var xmlBody = new XmlChildBody(body)) {
481 return postData(instanceIdentifier, xmlBody, uriInfo);
485 private Response postData(final ChildBody body, final UriInfo uriInfo) {
486 return postData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()), body,
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();
498 for (var arg : payload.prefix()) {
499 path = path.node(arg);
502 PostDataTransactionUtil.postData(path, data, strategy, context, params);
503 return Response.created(resolveLocation(uriInfo, path, context, data)).build();
507 * Get location from {@link YangInstanceIdentifier} and {@link UriInfo}.
509 * @param uriInfo uri info
510 * @param initialPath data path
511 * @param schemaContext reference to {@link SchemaContext}
512 * @return {@link URI}
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());
524 return uriInfo.getBaseUriBuilder().path("data").path(IdentifierCodec.serialize(path, schemaContext)).build();
528 * Delete the target data resource.
530 * @param identifier path to target
531 * @param ar {@link AsyncResponse} which needs to be completed
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());
541 Futures.addCallback(strategy.delete(instanceIdentifier.getInstanceIdentifier()), new FutureCallback<>() {
543 public void onSuccess(final Empty result) {
544 ar.resume(Response.noContent().build());
548 public void onFailure(final Throwable failure) {
551 }, MoreExecutors.directExecutor());
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>.
558 * @param body data node for put to config DS
559 * @param ar {@link AsyncResponse} which needs to be completed
564 MediaTypes.APPLICATION_YANG_DATA_XML,
565 MediaType.APPLICATION_XML,
568 public void plainPatchDataXML(final InputStream body, @Suspended final AsyncResponse ar) {
569 try (var xmlBody = new XmlResourceBody(body)) {
570 plainPatchData(null, xmlBody, ar);
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>.
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
583 @Path("/data/{identifier:.+}")
585 MediaTypes.APPLICATION_YANG_DATA_XML,
586 MediaType.APPLICATION_XML,
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);
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>.
600 * @param body data node for put to config DS
601 * @param ar {@link AsyncResponse} which needs to be completed
606 MediaTypes.APPLICATION_YANG_DATA_JSON,
607 MediaType.APPLICATION_JSON,
609 public void plainPatchDataJSON(final InputStream body, @Suspended final AsyncResponse ar) {
610 try (var jsonBody = new JsonResourceBody(body)) {
611 plainPatchData(null, jsonBody, ar);
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>.
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
624 @Path("/data/{identifier:.+}")
626 MediaTypes.APPLICATION_YANG_DATA_JSON,
627 MediaType.APPLICATION_JSON,
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);
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>.
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
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());
648 Futures.addCallback(future, new FutureCallback<>() {
650 public void onSuccess(final Empty result) {
651 ar.resume(Response.ok().build());
655 public void onFailure(final Throwable failure) {
658 }, MoreExecutors.directExecutor());
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(),
665 final var inference = context.inference();
666 final var path = context.getInstanceIdentifier();
667 final var data = body.toNormalizedNode(path, inference, context.getSchemaNode());
669 return new ResourceRequest(getRestconfStrategy(context.getMountPoint()), inference.getEffectiveModelContext(),
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>.
677 * @param identifier path to target
678 * @param body YANG Patch body
679 * @return {@link PatchStatusContext}
682 @Path("/data/{identifier:.+}")
683 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
685 MediaTypes.APPLICATION_YANG_DATA_JSON,
686 MediaTypes.APPLICATION_YANG_DATA_XML
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);
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>.
699 * @param body YANG Patch body
700 * @return {@link PatchStatusContext}
704 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
706 MediaTypes.APPLICATION_YANG_DATA_JSON,
707 MediaTypes.APPLICATION_YANG_DATA_XML
709 public PatchStatusContext yangPatchDataXML(final InputStream body) {
710 try (var xmlBody = new XmlPatchBody(body)) {
711 return yangPatchData(xmlBody);
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>.
719 * @param identifier path to target
720 * @param body YANG Patch body
721 * @return {@link PatchStatusContext}
724 @Path("/data/{identifier:.+}")
725 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
727 MediaTypes.APPLICATION_YANG_DATA_JSON,
728 MediaTypes.APPLICATION_YANG_DATA_XML
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);
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>.
741 * @param body YANG Patch body
742 * @return {@link PatchStatusContext}
746 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
748 MediaTypes.APPLICATION_YANG_DATA_JSON,
749 MediaTypes.APPLICATION_YANG_DATA_XML
751 public PatchStatusContext yangPatchDataJSON(final InputStream body) {
752 try (var jsonBody = new JsonPatchBody(body)) {
753 return yangPatchData(jsonBody);
757 private PatchStatusContext yangPatchData(final @NonNull PatchBody body) {
758 return yangPatchData(InstanceIdentifierContext.ofLocalRoot(databindProvider.currentContext().modelContext()),
762 private PatchStatusContext yangPatchData(final String identifier, final @NonNull PatchBody body) {
763 return yangPatchData(ParserIdentifier.toInstanceIdentifier(identifier,
764 databindProvider.currentContext().modelContext(), mountPointService), body);
767 private PatchStatusContext yangPatchData(final @NonNull InstanceIdentifierContext targetResource,
768 final @NonNull PatchBody body) {
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);
779 PatchStatusContext yangPatchData(final InstanceIdentifierContext targetResource, final PatchContext context) {
780 return PatchDataTransactionUtil.patchData(context, getRestconfStrategy(targetResource.getMountPoint()),
781 targetResource.getSchemaContext());
785 RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
786 if (mountPoint == null) {
787 return restconfStrategy;
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());
798 * Invoke Action operation.
800 * @param payload {@link NormalizedNodePayload} - the body of the operation
801 * @return {@link NormalizedNodePayload} wrapped in {@link Response}
803 private Response invokeAction(final InstanceIdentifierContext context, final OperationInputBody body) {
804 final var yangIIdContext = context.getInstanceIdentifier();
805 final ContainerNode input;
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);
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);
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();
824 return Response.status(Status.OK).entity(NormalizedNodePayload.ofNullable(context, resultData)).build();
828 * Invoking Action via mount point.
830 * @param mountPoint mount point
831 * @param data input data
832 * @param schemaPath schema path of data
833 * @return {@link DOMActionResult}
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.")));
842 * Invoke Action via ActionServiceHandler.
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}
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()));
862 * Check the validity of the result.
864 * @param response response of Action
865 * @return {@link DOMActionResult} result
867 private static DOMActionResult checkActionResponse(final DOMActionResult response) {
868 if (response == null) {
873 if (response.getErrors().isEmpty()) {
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);