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.RestconfDataServiceConstant.PostPutQueryParameters.INSERT;
12 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.PostPutQueryParameters.POINT;
13 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.NOTIFICATION_STREAM;
14 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
15 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
16 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
18 import java.time.Clock;
19 import java.time.LocalDateTime;
20 import java.time.format.DateTimeFormatter;
21 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Optional;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.WebApplicationException;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.core.UriInfo;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.mdsal.dom.api.DOMActionResult;
31 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
32 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
33 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
35 import org.opendaylight.restconf.common.context.WriterParameters;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
39 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchStatusContext;
42 import org.opendaylight.restconf.nb.rfc8040.handlers.ActionServiceHandler;
43 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
44 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
45 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
46 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
47 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
48 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
49 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
50 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
51 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
52 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil;
53 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
54 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
55 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
56 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
57 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfInvokeOperationsUtil;
58 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
59 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
60 import org.opendaylight.yangtools.concepts.Immutable;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.Revision;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * Implementation of {@link RestconfDataService}.
76 public class RestconfDataServiceImpl implements RestconfDataService {
77 private static final class QueryParams implements Immutable {
78 final @Nullable String point;
79 final @Nullable String insert;
81 QueryParams(final @Nullable String insert, final @Nullable String point) {
87 private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
88 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
90 private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
92 // FIXME: evaluate thread-safety of updates (synchronized) vs. access (mostly unsynchronized) here
93 private SchemaContextHandler schemaContextHandler;
94 private TransactionChainHandler transactionChainHandler;
95 private DOMMountPointServiceHandler mountPointServiceHandler;
96 private volatile ActionServiceHandler actionServiceHandler;
98 public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
99 final TransactionChainHandler transactionChainHandler,
100 final DOMMountPointServiceHandler mountPointServiceHandler,
101 final RestconfStreamsSubscriptionService delegRestconfSubscrService,
102 final ActionServiceHandler actionServiceHandler) {
103 this.actionServiceHandler = requireNonNull(actionServiceHandler);
104 this.schemaContextHandler = requireNonNull(schemaContextHandler);
105 this.transactionChainHandler = requireNonNull(transactionChainHandler);
106 this.mountPointServiceHandler = requireNonNull(mountPointServiceHandler);
107 this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
111 public synchronized void updateHandlers(final Object... handlers) {
112 for (final Object object : handlers) {
113 if (object instanceof SchemaContextHandler) {
114 schemaContextHandler = (SchemaContextHandler) object;
115 } else if (object instanceof ActionServiceHandler) {
116 actionServiceHandler = (ActionServiceHandler) object;
117 } else if (object instanceof DOMMountPointServiceHandler) {
118 mountPointServiceHandler = (DOMMountPointServiceHandler) object;
119 } else if (object instanceof TransactionChainHandler) {
120 transactionChainHandler = (TransactionChainHandler) object;
126 public Response readData(final UriInfo uriInfo) {
127 return readData(null, uriInfo);
131 public Response readData(final String identifier, final UriInfo uriInfo) {
132 final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
133 final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
134 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
135 final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
137 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
138 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
139 instanceIdentifier, mountPoint, getTransactionChainHandler(mountPoint));
140 final NormalizedNode<?, ?> node = ReadDataTransactionUtil.readData(identifier, parameters.getContent(),
141 transactionNode, parameters.getWithDefault(), schemaContextRef, uriInfo);
142 if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
143 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
144 final String value = (String) node.getValue();
145 final String streamName = value.substring(
146 value.indexOf(NOTIFICATION_STREAM + RestconfConstants.SLASH));
147 this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
150 throw new RestconfDocumentedException(
151 "Request could not be completed because the relevant data model content does not exist",
152 RestconfError.ErrorType.PROTOCOL,
153 RestconfError.ErrorTag.DATA_MISSING);
156 if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
157 || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
158 final QName type = node.getNodeType();
159 return Response.status(200)
160 .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
161 .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
162 + type.getLocalName() + '"')
163 .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
167 return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
171 public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
172 requireNonNull(payload);
174 final QueryParams checkedParms = checkQueryParameters(uriInfo);
176 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
177 .getInstanceIdentifierContext();
179 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
180 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
181 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
183 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
184 final TransactionChainHandler localTransactionChainHandler;
185 final SchemaContextRef ref;
186 if (mountPoint == null) {
187 localTransactionChainHandler = this.transactionChainHandler;
188 ref = new SchemaContextRef(this.schemaContextHandler.get());
190 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
191 ref = new SchemaContextRef(mountPoint.getEffectiveModelContext());
194 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
195 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
196 return PutDataTransactionUtil.putData(payload, ref, transactionNode, checkedParms.insert, checkedParms.point);
199 private static QueryParams checkQueryParameters(final UriInfo uriInfo) {
200 boolean insertUsed = false;
201 boolean pointUsed = false;
202 String insert = null;
205 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
206 switch (entry.getKey()) {
210 insert = entry.getValue().get(0);
212 throw new RestconfDocumentedException("Insert parameter can be used only once.",
213 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
219 point = entry.getValue().get(0);
221 throw new RestconfDocumentedException("Point parameter can be used only once.",
222 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
226 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
227 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
231 checkQueryParams(insertUsed, pointUsed, insert);
232 return new QueryParams(insert, point);
235 private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
236 if (pointUsed && !insertUsed) {
237 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
238 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
240 if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
241 throw new RestconfDocumentedException(
242 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
243 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
248 public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
249 return postData(payload, uriInfo);
253 public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
254 requireNonNull(payload);
255 if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
256 return invokeAction(payload, uriInfo);
259 final QueryParams checkedParms = checkQueryParameters(uriInfo);
261 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
262 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
263 payload.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
264 return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode,
265 getSchemaContext(mountPoint), checkedParms.insert, checkedParms.point);
269 public Response deleteData(final String identifier) {
270 final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
271 final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
272 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
274 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
275 final TransactionChainHandler localTransactionChainHandler;
276 if (mountPoint == null) {
277 localTransactionChainHandler = this.transactionChainHandler;
279 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
282 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
283 localTransactionChainHandler);
284 return DeleteDataTransactionUtil.deleteData(transactionNode);
288 public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
289 return patchData(context, uriInfo);
293 public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
294 final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
295 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
296 context.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
297 return PatchDataTransactionUtil.patchData(context, transactionNode, getSchemaContext(mountPoint));
301 public Response patchData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
302 requireNonNull(payload);
304 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
305 .getInstanceIdentifierContext();
307 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
308 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
309 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
311 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
312 final TransactionChainHandler localTransactionChainHandler;
313 final SchemaContextRef ref;
314 if (mountPoint == null) {
315 localTransactionChainHandler = this.transactionChainHandler;
316 ref = new SchemaContextRef(this.schemaContextHandler.get());
318 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
319 ref = new SchemaContextRef(mountPoint.getEffectiveModelContext());
322 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
323 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
325 return PlainPatchDataTransactionUtil.patchData(payload, transactionNode, ref);
328 private TransactionChainHandler getTransactionChainHandler(final DOMMountPoint mountPoint) {
329 return mountPoint == null ? transactionChainHandler : transactionChainOfMountPoint(mountPoint);
332 private SchemaContextRef getSchemaContext(final DOMMountPoint mountPoint) {
333 return mountPoint == null ? new SchemaContextRef(schemaContextHandler.get())
334 : new SchemaContextRef(mountPoint.getEffectiveModelContext());
338 * Prepare transaction chain to access data of mount point.
340 * mount point reference
341 * @return {@link TransactionChainHandler}
343 private static TransactionChainHandler transactionChainOfMountPoint(final @NonNull DOMMountPoint mountPoint) {
344 final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
345 if (domDataBrokerService.isPresent()) {
346 return new TransactionChainHandler(domDataBrokerService.get());
349 final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
351 throw new RestconfDocumentedException(errMsg);
355 * Invoke Action operation.
358 * {@link NormalizedNodeContext} - the body of the operation
361 * @return {@link NormalizedNodeContext} wrapped in {@link Response}
363 public Response invokeAction(final NormalizedNodeContext payload, final UriInfo uriInfo) {
364 final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
365 final DOMMountPoint mountPoint = context.getMountPoint();
366 final SchemaPath schemaPath = context.getSchemaNode().getPath();
367 final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
368 final NormalizedNode<?, ?> data = payload.getData();
370 if (yangIIdContext.isEmpty() && !RestconfDataServiceConstant.NETCONF_BASE_QNAME.equals(data.getNodeType())) {
371 throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
372 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
375 final DOMActionResult response;
376 final SchemaContextRef schemaContextRef;
377 if (mountPoint != null) {
378 response = RestconfInvokeOperationsUtil.invokeActionViaMountPoint(mountPoint, (ContainerNode) data,
379 schemaPath, yangIIdContext);
380 schemaContextRef = new SchemaContextRef(mountPoint.getEffectiveModelContext());
382 response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
383 this.actionServiceHandler, yangIIdContext);
384 schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
386 final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
388 ActionDefinition resultNodeSchema = null;
389 ContainerNode resultData = null;
390 if (result != null) {
391 final Optional<ContainerNode> optOutput = result.getOutput();
392 if (optOutput.isPresent()) {
393 resultData = optOutput.get();
394 resultNodeSchema = (ActionDefinition) context.getSchemaNode();
398 if (resultData != null && resultData.getValue().isEmpty()) {
399 throw new WebApplicationException(Response.Status.NO_CONTENT);
402 return Response.status(200).entity(new NormalizedNodeContext(new InstanceIdentifierContext<>(yangIIdContext,
403 resultNodeSchema, mountPoint, schemaContextRef.get()), resultData)).build();