Refactoring of web-sockets in RESTCONF RFC-8040
[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
107         boolean withDefaUsed = false;
108         String withDefa = null;
109
110         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
111             switch (entry.getKey()) {
112                 case "with-defaults":
113                     if (!withDefaUsed) {
114                         withDefaUsed = true;
115                         withDefa = entry.getValue().iterator().next();
116                     } else {
117                         throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
118                     }
119                     break;
120                 default:
121                     LOG.info("Unknown key : {}.", entry.getKey());
122                     break;
123             }
124         }
125         boolean tagged = false;
126         if (withDefaUsed) {
127             if ("report-all-tagged".equals(withDefa)) {
128                 tagged = true;
129                 withDefa = null;
130             }
131             if ("report-all".equals(withDefa)) {
132                 withDefa = null;
133             }
134         }
135
136         final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(
137                 instanceIdentifier, uriInfo, tagged);
138
139         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
140         final TransactionChainHandler localTransactionChainHandler;
141         if (mountPoint == null) {
142             localTransactionChainHandler = this.transactionChainHandler;
143         } else {
144             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
145         }
146
147         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
148                 instanceIdentifier, mountPoint, localTransactionChainHandler);
149         final NormalizedNode<?, ?> node =
150                 ReadDataTransactionUtil.readData(identifier, parameters.getContent(), transactionNode, withDefa,
151                         schemaContextRef, uriInfo);
152         if (identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
153                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
154             final String value = (String) node.getValue();
155             final String streamName = value.substring(
156                     value.indexOf(CREATE_NOTIFICATION_STREAM + RestconfConstants.SLASH));
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         requireNonNull(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 TransactionChainHandler localTransactionChainHandler;
223         final SchemaContextRef ref;
224         if (mountPoint == null) {
225             localTransactionChainHandler = this.transactionChainHandler;
226             ref = new SchemaContextRef(this.schemaContextHandler.get());
227         } else {
228             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
229             ref = new SchemaContextRef(mountPoint.getSchemaContext());
230         }
231
232         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
233                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
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         requireNonNull(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 TransactionChainHandler localTransactionChainHandler;
288         final SchemaContextRef ref;
289         if (mountPoint == null) {
290             localTransactionChainHandler = this.transactionChainHandler;
291             ref = new SchemaContextRef(this.schemaContextHandler.get());
292         } else {
293             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
294             ref = new SchemaContextRef(mountPoint.getSchemaContext());
295         }
296         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
297                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
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 TransactionChainHandler localTransactionChainHandler;
309         if (mountPoint == null) {
310             localTransactionChainHandler = this.transactionChainHandler;
311         } else {
312             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
313         }
314
315         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
316                 localTransactionChainHandler);
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         final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
328
329         final TransactionChainHandler localTransactionChainHandler;
330         final SchemaContextRef ref;
331         if (mountPoint == null) {
332             localTransactionChainHandler = this.transactionChainHandler;
333             ref = new SchemaContextRef(this.schemaContextHandler.get());
334         } else {
335             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
336             ref = new SchemaContextRef(mountPoint.getSchemaContext());
337         }
338
339         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
340                 context.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
341
342         return PatchDataTransactionUtil.patchData(context, transactionNode, ref);
343     }
344
345     /**
346      * Prepare transaction chain to access data of mount point.
347      * @param mountPoint
348      *            mount point reference
349      * @return {@link TransactionChainHandler}
350      */
351     private static TransactionChainHandler transactionChainOfMountPoint(final @NonNull DOMMountPoint mountPoint) {
352         final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
353         if (domDataBrokerService.isPresent()) {
354             return new TransactionChainHandler(domDataBrokerService.get());
355         }
356
357         final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
358         LOG.warn(errMsg);
359         throw new RestconfDocumentedException(errMsg);
360     }
361 }