Fixed response errors for HTTP PUT
[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.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 java.util.Objects;
22 import java.util.Optional;
23 import javax.annotation.Nonnull;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.core.Response;
26 import javax.ws.rs.core.UriInfo;
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.toString() + RestconfConstants.SLASH),
157                     value.length());
158             this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
159         }
160         if (node == null) {
161             throw new RestconfDocumentedException(
162                     "Request could not be completed because the relevant data model content does not exist",
163                     RestconfError.ErrorType.PROTOCOL,
164                     RestconfError.ErrorTag.DATA_MISSING);
165         }
166
167         if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
168                     || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
169             final QName type = node.getNodeType();
170             return Response.status(200)
171                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
172                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
173                         + type.getLocalName() + '"')
174                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
175                     .build();
176         }
177
178         return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
179     }
180
181     @Override
182     public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
183         Preconditions.checkNotNull(payload);
184
185         boolean insertUsed = false;
186         boolean pointUsed = false;
187         String insert = null;
188         String point = null;
189
190         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
191             switch (entry.getKey()) {
192                 case "insert":
193                     if (!insertUsed) {
194                         insertUsed = true;
195                         insert = entry.getValue().iterator().next();
196                     } else {
197                         throw new RestconfDocumentedException("Insert parameter can be used only once.",
198                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
199                     }
200                     break;
201                 case "point":
202                     if (!pointUsed) {
203                         pointUsed = true;
204                         point = entry.getValue().iterator().next();
205                     } else {
206                         throw new RestconfDocumentedException("Point parameter can be used only once.",
207                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
208                     }
209                     break;
210                 default:
211                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
212                             RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
213             }
214         }
215
216         checkQueryParams(insertUsed, pointUsed, insert);
217
218         final InstanceIdentifierContext<? extends SchemaNode> iid = payload
219                 .getInstanceIdentifierContext();
220
221         PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
222         PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
223         PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
224
225         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
226         final TransactionChainHandler localTransactionChainHandler;
227         final SchemaContextRef ref;
228         if (mountPoint == null) {
229             localTransactionChainHandler = this.transactionChainHandler;
230             ref = new SchemaContextRef(this.schemaContextHandler.get());
231         } else {
232             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
233             ref = new SchemaContextRef(mountPoint.getSchemaContext());
234         }
235
236         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
237                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
238         return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
239     }
240
241     private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
242         if (pointUsed && !insertUsed) {
243             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
244         }
245         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
246             throw new RestconfDocumentedException(
247                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
248         }
249     }
250
251     @Override
252     public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
253         return postData(payload, uriInfo);
254     }
255
256     @Override
257     public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
258         Preconditions.checkNotNull(payload);
259
260         boolean insertUsed = false;
261         boolean pointUsed = false;
262         String insert = null;
263         String point = null;
264
265         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
266             switch (entry.getKey()) {
267                 case "insert":
268                     if (!insertUsed) {
269                         insertUsed = true;
270                         insert = entry.getValue().iterator().next();
271                     } else {
272                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
273                     }
274                     break;
275                 case "point":
276                     if (!pointUsed) {
277                         pointUsed = true;
278                         point = entry.getValue().iterator().next();
279                     } else {
280                         throw new RestconfDocumentedException("Point parameter can be used only once.");
281                     }
282                     break;
283                 default:
284                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
285             }
286         }
287
288         checkQueryParams(insertUsed, pointUsed, insert);
289
290         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
291         final TransactionChainHandler localTransactionChainHandler;
292         final SchemaContextRef ref;
293         if (mountPoint == null) {
294             localTransactionChainHandler = this.transactionChainHandler;
295             ref = new SchemaContextRef(this.schemaContextHandler.get());
296         } else {
297             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
298             ref = new SchemaContextRef(mountPoint.getSchemaContext());
299         }
300         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
301                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
302         return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode, ref, insert, point);
303     }
304
305     @Override
306     public Response deleteData(final String identifier) {
307         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
308         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
309                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
310
311         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
312         final TransactionChainHandler localTransactionChainHandler;
313         if (mountPoint == null) {
314             localTransactionChainHandler = this.transactionChainHandler;
315         } else {
316             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
317         }
318
319         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
320                 localTransactionChainHandler);
321         return DeleteDataTransactionUtil.deleteData(transactionNode);
322     }
323
324     @Override
325     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
326         return patchData(context, uriInfo);
327     }
328
329     @Override
330     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
331         Preconditions.checkNotNull(context);
332         final DOMMountPoint mountPoint = context.getInstanceIdentifierContext().getMountPoint();
333
334         final TransactionChainHandler localTransactionChainHandler;
335         final SchemaContextRef ref;
336         if (mountPoint == null) {
337             localTransactionChainHandler = this.transactionChainHandler;
338             ref = new SchemaContextRef(this.schemaContextHandler.get());
339         } else {
340             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
341             ref = new SchemaContextRef(mountPoint.getSchemaContext());
342         }
343
344         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
345                 context.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
346
347         return PatchDataTransactionUtil.patchData(context, transactionNode, ref);
348     }
349
350     /**
351      * Prepare transaction chain to access data of mount point.
352      * @param mountPoint
353      *            mount point reference
354      * @return {@link TransactionChainHandler}
355      */
356     private static TransactionChainHandler transactionChainOfMountPoint(@Nonnull final DOMMountPoint mountPoint) {
357         final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
358         if (domDataBrokerService.isPresent()) {
359             return new TransactionChainHandler(domDataBrokerService.get());
360         }
361
362         final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
363         LOG.warn(errMsg);
364         throw new RestconfDocumentedException(errMsg);
365     }
366 }