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