Fixed POST data error response
[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 TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
110                 instanceIdentifier, mountPoint, getTransactionChainHandler(mountPoint));
111         final NormalizedNode<?, ?> node = ReadDataTransactionUtil.readData(identifier, parameters.getContent(),
112                 transactionNode, parameters.getWithDefault(), schemaContextRef, uriInfo);
113         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
114                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
115             final String value = (String) node.getValue();
116             final String streamName = value.substring(
117                     value.indexOf(CREATE_NOTIFICATION_STREAM + RestconfConstants.SLASH));
118             this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
119         }
120         if (node == null) {
121             throw new RestconfDocumentedException(
122                     "Request could not be completed because the relevant data model content does not exist",
123                     RestconfError.ErrorType.PROTOCOL,
124                     RestconfError.ErrorTag.DATA_MISSING);
125         }
126
127         if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
128                     || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
129             final QName type = node.getNodeType();
130             return Response.status(200)
131                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
132                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
133                         + type.getLocalName() + '"')
134                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
135                     .build();
136         }
137
138         return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
139     }
140
141     @Override
142     public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
143         requireNonNull(payload);
144
145         boolean insertUsed = false;
146         boolean pointUsed = false;
147         String insert = null;
148         String point = null;
149
150         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
151             switch (entry.getKey()) {
152                 case "insert":
153                     if (!insertUsed) {
154                         insertUsed = true;
155                         insert = entry.getValue().iterator().next();
156                     } else {
157                         throw new RestconfDocumentedException("Insert parameter can be used only once.");
158                     }
159                     break;
160                 case "point":
161                     if (!pointUsed) {
162                         pointUsed = true;
163                         point = entry.getValue().iterator().next();
164                     } else {
165                         throw new RestconfDocumentedException("Point parameter can be used only once.");
166                     }
167                     break;
168                 default:
169                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey());
170             }
171         }
172
173         checkQueryParams(insertUsed, pointUsed, insert);
174
175         final InstanceIdentifierContext<? extends SchemaNode> iid = payload
176                 .getInstanceIdentifierContext();
177
178         PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
179         PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
180         PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
181
182         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
183         final TransactionChainHandler localTransactionChainHandler;
184         final SchemaContextRef ref;
185         if (mountPoint == null) {
186             localTransactionChainHandler = this.transactionChainHandler;
187             ref = new SchemaContextRef(this.schemaContextHandler.get());
188         } else {
189             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
190             ref = new SchemaContextRef(mountPoint.getSchemaContext());
191         }
192
193         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
194                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
195         return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
196     }
197
198     private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
199         if (pointUsed && !insertUsed) {
200             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
201                     RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
202         }
203         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
204             throw new RestconfDocumentedException(
205                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
206                     RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
207         }
208     }
209
210     @Override
211     public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
212         return postData(payload, uriInfo);
213     }
214
215     @Override
216     public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
217         requireNonNull(payload);
218
219         boolean insertUsed = false;
220         boolean pointUsed = false;
221         String insert = null;
222         String point = null;
223
224         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
225             switch (entry.getKey()) {
226                 case "insert":
227                     if (!insertUsed) {
228                         insertUsed = true;
229                         insert = entry.getValue().iterator().next();
230                     } else {
231                         throw new RestconfDocumentedException("Insert parameter can be used only once.",
232                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
233                     }
234                     break;
235                 case "point":
236                     if (!pointUsed) {
237                         pointUsed = true;
238                         point = entry.getValue().iterator().next();
239                     } else {
240                         throw new RestconfDocumentedException("Point parameter can be used only once.",
241                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
242                     }
243                     break;
244                 default:
245                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
246                             RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
247             }
248         }
249
250         checkQueryParams(insertUsed, pointUsed, insert);
251
252         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
253         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
254                 payload.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
255         return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode,
256                 getSchemaContext(mountPoint), insert, point);
257     }
258
259     @Override
260     public Response deleteData(final String identifier) {
261         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
262         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
263                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
264
265         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
266         final TransactionChainHandler localTransactionChainHandler;
267         if (mountPoint == null) {
268             localTransactionChainHandler = this.transactionChainHandler;
269         } else {
270             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
271         }
272
273         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
274                 localTransactionChainHandler);
275         return DeleteDataTransactionUtil.deleteData(transactionNode);
276     }
277
278     @Override
279     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
280         return patchData(context, uriInfo);
281     }
282
283     @Override
284     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
285         final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
286         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
287                 context.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
288         return PatchDataTransactionUtil.patchData(context, transactionNode, getSchemaContext(mountPoint));
289     }
290
291     private TransactionChainHandler getTransactionChainHandler(final DOMMountPoint mountPoint) {
292         return mountPoint == null ? transactionChainHandler : transactionChainOfMountPoint(mountPoint);
293     }
294
295     private SchemaContextRef getSchemaContext(final DOMMountPoint mountPoint) {
296         return mountPoint == null ? new SchemaContextRef(schemaContextHandler.get())
297                 : new SchemaContextRef(mountPoint.getSchemaContext());
298     }
299
300     /**
301      * Prepare transaction chain to access data of mount point.
302      * @param mountPoint
303      *            mount point reference
304      * @return {@link TransactionChainHandler}
305      */
306     private static TransactionChainHandler transactionChainOfMountPoint(final @NonNull DOMMountPoint mountPoint) {
307         final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
308         if (domDataBrokerService.isPresent()) {
309             return new TransactionChainHandler(domDataBrokerService.get());
310         }
311
312         final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
313         LOG.warn(errMsg);
314         throw new RestconfDocumentedException(errMsg);
315     }
316 }