b0dcebd66ab55ffcf51046329791b76f4b98364c
[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.CREATE_NOTIFICATION_STREAM;
12 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
13 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
14 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
15
16 import java.time.Clock;
17 import java.time.LocalDateTime;
18 import java.time.format.DateTimeFormatter;
19 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.Objects;
22 import java.util.Optional;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.core.Response;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
28 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
31 import org.opendaylight.restconf.common.context.WriterParameters;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.common.errors.RestconfError;
34 import org.opendaylight.restconf.common.patch.PatchContext;
35 import org.opendaylight.restconf.common.patch.PatchStatusContext;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
37 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
38 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
39 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
40 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
41 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
42 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
43 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
44 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
45 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
46 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
47 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
48 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
49 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
50 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.Revision;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Implementation of {@link RestconfDataService}.
60  */
61 @Path("/")
62 public class RestconfDataServiceImpl implements RestconfDataService {
63
64     private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
65     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
66
67     private SchemaContextHandler schemaContextHandler;
68     private TransactionChainHandler transactionChainHandler;
69     private DOMMountPointServiceHandler mountPointServiceHandler;
70
71     private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
72
73     public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
74                                    final TransactionChainHandler transactionChainHandler,
75             final DOMMountPointServiceHandler mountPointServiceHandler,
76             final RestconfStreamsSubscriptionService delegRestconfSubscrService) {
77         this.schemaContextHandler = Objects.requireNonNull(schemaContextHandler);
78         this.transactionChainHandler = Objects.requireNonNull(transactionChainHandler);
79         this.mountPointServiceHandler = Objects.requireNonNull(mountPointServiceHandler);
80         this.delegRestconfSubscrService = Objects.requireNonNull(delegRestconfSubscrService);
81     }
82
83     @Override
84     public synchronized void updateHandlers(final Object... handlers) {
85         for (final Object object : handlers) {
86             if (object instanceof SchemaContextHandler) {
87                 schemaContextHandler = (SchemaContextHandler) object;
88             } else if (object instanceof DOMMountPointServiceHandler) {
89                 mountPointServiceHandler = (DOMMountPointServiceHandler) object;
90             } else if (object instanceof TransactionChainHandler) {
91                 transactionChainHandler = (TransactionChainHandler) object;
92             }
93         }
94     }
95
96     @Override
97     public Response readData(final UriInfo uriInfo) {
98         return readData(null, uriInfo);
99     }
100
101     @Override
102     public Response readData(final String identifier, final UriInfo uriInfo) {
103         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
104         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
105                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
106         final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
107
108         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
109         final TransactionChainHandler localTransactionChainHandler;
110         if (mountPoint == null) {
111             localTransactionChainHandler = this.transactionChainHandler;
112         } else {
113             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
114         }
115
116         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
117                 instanceIdentifier, mountPoint, localTransactionChainHandler);
118         final NormalizedNode<?, ?> node = ReadDataTransactionUtil.readData(identifier, parameters.getContent(),
119                 transactionNode, parameters.getWithDefault(), schemaContextRef, uriInfo);
120         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
121                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
122             final String value = (String) node.getValue();
123             final String streamName = value.substring(
124                     value.indexOf(CREATE_NOTIFICATION_STREAM + RestconfConstants.SLASH));
125             this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
126         }
127         if (node == null) {
128             throw new RestconfDocumentedException(
129                     "Request could not be completed because the relevant data model content does not exist",
130                     RestconfError.ErrorType.PROTOCOL,
131                     RestconfError.ErrorTag.DATA_MISSING);
132         }
133
134         if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
135                     || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
136             final QName type = node.getNodeType();
137             return Response.status(200)
138                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
139                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
140                         + type.getLocalName() + '"')
141                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
142                     .build();
143         }
144
145         return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
146     }
147
148     @Override
149     public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
150         requireNonNull(payload);
151
152         boolean insertUsed = false;
153         boolean pointUsed = false;
154         String insert = null;
155         String point = null;
156
157         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
158             switch (entry.getKey()) {
159                 case "insert":
160                     if (!insertUsed) {
161                         insertUsed = true;
162                         insert = entry.getValue().iterator().next();
163                     } else {
164                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
165                     }
166                     break;
167                 case "point":
168                     if (!pointUsed) {
169                         pointUsed = true;
170                         point = entry.getValue().iterator().next();
171                     } else {
172                         throw new RestconfDocumentedException("Point parameter can be used only once.");
173                     }
174                     break;
175                 default:
176                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
177             }
178         }
179
180         checkQueryParams(insertUsed, pointUsed, insert);
181
182         final InstanceIdentifierContext<? extends SchemaNode> iid = payload
183                 .getInstanceIdentifierContext();
184
185         PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
186         PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
187         PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
188
189         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
190         final TransactionChainHandler localTransactionChainHandler;
191         final SchemaContextRef ref;
192         if (mountPoint == null) {
193             localTransactionChainHandler = this.transactionChainHandler;
194             ref = new SchemaContextRef(this.schemaContextHandler.get());
195         } else {
196             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
197             ref = new SchemaContextRef(mountPoint.getSchemaContext());
198         }
199
200         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
201                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
202         return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
203     }
204
205     private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
206         if (pointUsed && !insertUsed) {
207             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
208         }
209         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
210             throw new RestconfDocumentedException(
211                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
212         }
213     }
214
215     @Override
216     public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
217         return postData(payload, uriInfo);
218     }
219
220     @Override
221     public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
222         requireNonNull(payload);
223
224         boolean insertUsed = false;
225         boolean pointUsed = false;
226         String insert = null;
227         String point = null;
228
229         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
230             switch (entry.getKey()) {
231                 case "insert":
232                     if (!insertUsed) {
233                         insertUsed = true;
234                         insert = entry.getValue().iterator().next();
235                     } else {
236                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
237                     }
238                     break;
239                 case "point":
240                     if (!pointUsed) {
241                         pointUsed = true;
242                         point = entry.getValue().iterator().next();
243                     } else {
244                         throw new RestconfDocumentedException("Point parameter can be used only once.");
245                     }
246                     break;
247                 default:
248                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
249             }
250         }
251
252         checkQueryParams(insertUsed, pointUsed, insert);
253
254         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
255         final TransactionChainHandler localTransactionChainHandler;
256         final SchemaContextRef ref;
257         if (mountPoint == null) {
258             localTransactionChainHandler = this.transactionChainHandler;
259             ref = new SchemaContextRef(this.schemaContextHandler.get());
260         } else {
261             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
262             ref = new SchemaContextRef(mountPoint.getSchemaContext());
263         }
264         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
265                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
266         return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode, ref, insert, point);
267     }
268
269     @Override
270     public Response deleteData(final String identifier) {
271         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
272         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
273                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
274
275         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
276         final TransactionChainHandler localTransactionChainHandler;
277         if (mountPoint == null) {
278             localTransactionChainHandler = this.transactionChainHandler;
279         } else {
280             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
281         }
282
283         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
284                 localTransactionChainHandler);
285         return DeleteDataTransactionUtil.deleteData(transactionNode);
286     }
287
288     @Override
289     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
290         return patchData(context, uriInfo);
291     }
292
293     @Override
294     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
295         final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
296
297         final TransactionChainHandler localTransactionChainHandler;
298         final SchemaContextRef ref;
299         if (mountPoint == null) {
300             localTransactionChainHandler = this.transactionChainHandler;
301             ref = new SchemaContextRef(this.schemaContextHandler.get());
302         } else {
303             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
304             ref = new SchemaContextRef(mountPoint.getSchemaContext());
305         }
306
307         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
308                 context.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
309
310         return PatchDataTransactionUtil.patchData(context, transactionNode, ref);
311     }
312
313     /**
314      * Prepare transaction chain to access data of mount point.
315      * @param mountPoint
316      *            mount point reference
317      * @return {@link TransactionChainHandler}
318      */
319     private static TransactionChainHandler transactionChainOfMountPoint(final @NonNull DOMMountPoint mountPoint) {
320         final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
321         if (domDataBrokerService.isPresent()) {
322             return new TransactionChainHandler(domDataBrokerService.get());
323         }
324
325         final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
326         LOG.warn(errMsg);
327         throw new RestconfDocumentedException(errMsg);
328     }
329 }