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