Remove RestconfError.ErrorType
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfDataServiceImpl.java
index 82a4f4dcb7979219790a4594206c465a924f0882..12d1e5f6d49c103910bfd201ed3d70c079780c33 100644 (file)
@@ -17,12 +17,15 @@ import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsCo
 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import java.net.URI;
 import java.time.Clock;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.concurrent.ExecutionException;
@@ -35,6 +38,8 @@ import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.mdsal.dom.api.DOMActionResult;
 import org.opendaylight.mdsal.dom.api.DOMActionService;
 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
@@ -44,7 +49,6 @@ import org.opendaylight.restconf.common.context.WriterParameters;
 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
 import org.opendaylight.restconf.common.errors.RestconfError;
 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
-import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
 import org.opendaylight.restconf.common.patch.PatchContext;
 import org.opendaylight.restconf.common.patch.PatchStatusContext;
 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
@@ -53,7 +57,6 @@ import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataServi
 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
-import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfTransaction;
 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil;
@@ -69,14 +72,18 @@ import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUti
 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.common.ErrorType;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
@@ -108,12 +115,14 @@ public class RestconfDataServiceImpl implements RestconfDataService {
     private final DOMMountPointService mountPointService;
     private final SubscribeToStreamUtil streamUtils;
     private final DOMActionService actionService;
+    private final DOMDataBroker dataBroker;
 
     public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
             final DOMDataBroker dataBroker, final DOMMountPointService  mountPointService,
             final RestconfStreamsSubscriptionService delegRestconfSubscrService,
             final DOMActionService actionService, final Configuration configuration) {
         this.schemaContextHandler = requireNonNull(schemaContextHandler);
+        this.dataBroker = requireNonNull(dataBroker);
         this.restconfStrategy = new MdsalRestconfStrategy(dataBroker);
         this.mountPointService = requireNonNull(mountPointService);
         this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
@@ -135,15 +144,23 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
 
         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
+
+        // FIXME: this looks quite crazy, why do we even have it?
+        if (mountPoint == null && identifier != null && identifier.contains(STREAMS_PATH)
+            && !identifier.contains(STREAM_PATH_PART)) {
+            createAllYangNotificationStreams(schemaContextRef, uriInfo);
+        }
+
         final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
         final NormalizedNode node;
         if (parameters.getFieldPaths() != null && !parameters.getFieldPaths().isEmpty()) {
             node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
                     strategy, parameters.getWithDefault(), schemaContextRef, parameters.getFieldPaths());
         } else {
-            node = readData(identifier, parameters.getContent(), instanceIdentifier.getInstanceIdentifier(), strategy,
-                    parameters.getWithDefault(), schemaContextRef, uriInfo);
+            node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
+                    strategy, parameters.getWithDefault(), schemaContextRef);
         }
+
         // FIXME: this is utter craziness, refactor it properly!
         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
@@ -154,8 +171,7 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         if (node == null) {
             throw new RestconfDocumentedException(
                     "Request could not be completed because the relevant data model content does not exist",
-                    RestconfError.ErrorType.PROTOCOL,
-                    RestconfError.ErrorTag.DATA_MISSING);
+                    ErrorType.PROTOCOL, RestconfError.ErrorTag.DATA_MISSING);
         }
 
         if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
@@ -172,40 +188,15 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
     }
 
-    /**
-     * Read specific type of data from data store via transaction and if identifier read data from
-     * streams then put streams from actual schema context to datastore.
-     *
-     * @param identifier    identifier of data to read
-     * @param content       type of data to read (config, state, all)
-     * @param strategy      {@link RestconfStrategy} - object that perform the actual DS operations
-     * @param withDefa      value of with-defaults parameter
-     * @param schemaContext schema context
-     * @param uriInfo       uri info
-     * @return {@link NormalizedNode}
-     */
-    private NormalizedNode readData(final String identifier, final String content,
-            final YangInstanceIdentifier path, final RestconfStrategy strategy, final String withDefa,
-            final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
-        if (identifier != null && identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
-            createAllYangNotificationStreams(strategy, schemaContext, uriInfo);
-        }
-        return ReadDataTransactionUtil.readData(content, path, strategy, withDefa, schemaContext);
-    }
-
-    private void createAllYangNotificationStreams(final RestconfStrategy strategy,
-            final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
-        final RestconfTransaction transaction = strategy.prepareWriteExecution();
-
+    private void createAllYangNotificationStreams(final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
+        final DOMDataTreeWriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
         for (final NotificationDefinition notificationDefinition : schemaContext.getNotifications()) {
-            final NotificationListenerAdapter notifiStreamXML =
+            writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
-                    NotificationOutputType.XML);
-            final NotificationListenerAdapter notifiStreamJSON =
+                    NotificationOutputType.XML));
+            writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction,
                 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
-                    NotificationOutputType.JSON);
-            writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction, notifiStreamXML);
-            writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction, notifiStreamJSON);
+                    NotificationOutputType.JSON));
         }
         try {
             transaction.commit().get();
@@ -215,13 +206,13 @@ public class RestconfDataServiceImpl implements RestconfDataService {
     }
 
     private void writeNotificationStreamToDatastore(final EffectiveModelContext schemaContext,
-            final UriInfo uriInfo, final RestconfTransaction transaction, final NotificationListenerAdapter listener) {
+            final UriInfo uriInfo, final DOMDataTreeWriteOperations tx, final NotificationListenerAdapter listener) {
         final URI uri = streamUtils.prepareUriByStreamName(uriInfo, listener.getStreamName());
         final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
                 listener.getSchemaPath().lastNodeIdentifier(), schemaContext.getNotifications(), null,
                 listener.getOutputType(), uri);
 
-        transaction.merge(LogicalDatastoreType.OPERATIONAL,
+        tx.merge(LogicalDatastoreType.OPERATIONAL,
             Rfc8040.restconfStateStreamPath(mapToStreams.getIdentifier()), mapToStreams);
     }
 
@@ -233,9 +224,9 @@ public class RestconfDataServiceImpl implements RestconfDataService {
 
         final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
 
-        PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
-        PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
-        PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
+        validInputData(iid.getSchemaNode(), payload);
+        validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
+        validateListKeysEqualityInPayloadAndUri(payload);
 
         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
         final EffectiveModelContext ref = mountPoint == null
@@ -256,7 +247,7 @@ public class RestconfDataServiceImpl implements RestconfDataService {
                 case INSERT:
                     if (insertUsed) {
                         throw new RestconfDocumentedException("Insert parameter can be used only once.",
-                            RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                            ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
                     }
 
                     insertUsed = true;
@@ -264,13 +255,13 @@ public class RestconfDataServiceImpl implements RestconfDataService {
                     insert = Insert.forValue(str);
                     if (insert == null) {
                         throw new RestconfDocumentedException("Unrecognized insert parameter value '" + str + "'",
-                            RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                            ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
                     }
                     break;
                 case POINT:
                     if (pointUsed) {
                         throw new RestconfDocumentedException("Point parameter can be used only once.",
-                            RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                            ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
                     }
 
                     pointUsed = true;
@@ -278,7 +269,7 @@ public class RestconfDataServiceImpl implements RestconfDataService {
                     break;
                 default:
                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
-                            RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                            ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
             }
         }
 
@@ -290,13 +281,13 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         if (pointUsed) {
             if (!insertUsed) {
                 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
-                    RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                    ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
             }
 
             if (insert != Insert.BEFORE && insert != Insert.AFTER) {
                 throw new RestconfDocumentedException(
                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
-                    RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
+                    ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
             }
         }
     }
@@ -349,9 +340,9 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         final InstanceIdentifierContext<? extends SchemaNode> iid = payload
                 .getInstanceIdentifierContext();
 
-        PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
-        PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
-        PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
+        validInputData(iid.getSchemaNode(), payload);
+        validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
+        validateListKeysEqualityInPayloadAndUri(payload);
 
         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
         final EffectiveModelContext ref = mountPoint == null
@@ -401,12 +392,12 @@ public class RestconfDataServiceImpl implements RestconfDataService {
         final DOMActionResult response;
         final EffectiveModelContext schemaContextRef;
         if (mountPoint != null) {
-            response = RestconfInvokeOperationsUtil.invokeActionViaMountPoint(mountPoint, (ContainerNode) data,
-                schemaPath, yangIIdContext);
+            response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath, yangIIdContext,
+                mountPoint);
             schemaContextRef = modelContext(mountPoint);
         } else {
-            response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
-                this.actionService, yangIIdContext);
+            response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath, yangIIdContext,
+                actionService);
             schemaContextRef = this.schemaContextHandler.get();
         }
         final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
@@ -429,6 +420,88 @@ public class RestconfDataServiceImpl implements RestconfDataService {
                 resultNodeSchema, mountPoint, schemaContextRef), resultData)).build();
     }
 
+    /**
+     * Valid input data with {@link SchemaNode}.
+     *
+     * @param schemaNode {@link SchemaNode}
+     * @param payload    input data
+     */
+    @VisibleForTesting
+    public static void validInputData(final SchemaNode schemaNode, final NormalizedNodeContext payload) {
+        if (schemaNode != null && payload.getData() == null) {
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        } else if (schemaNode == null && payload.getData() != null) {
+            throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        }
+    }
+
+    /**
+     * Valid top level node name.
+     *
+     * @param path    path of node
+     * @param payload data
+     */
+    @VisibleForTesting
+    public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
+        final String payloadName = payload.getData().getIdentifier().getNodeType().getLocalName();
+
+        if (path.isEmpty()) {
+            if (!payload.getData().getIdentifier().getNodeType().equals(
+                RestconfDataServiceConstant.NETCONF_BASE_QNAME)) {
+                throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
+                        ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+            }
+        } else {
+            final String identifierName = path.getLastPathArgument().getNodeType().getLocalName();
+            if (!payloadName.equals(identifierName)) {
+                throw new RestconfDocumentedException(
+                        "Payload name (" + payloadName + ") is different from identifier name (" + identifierName + ")",
+                        ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+            }
+        }
+    }
+
+
+    /**
+     * Validates whether keys in {@code payload} are equal to values of keys in
+     * {@code iiWithData} for list schema node.
+     *
+     * @throws RestconfDocumentedException if key values or key count in payload and URI isn't equal
+     */
+    @VisibleForTesting
+    public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
+        final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
+        final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
+        final SchemaNode schemaNode = iiWithData.getSchemaNode();
+        final NormalizedNode data = payload.getData();
+        if (schemaNode instanceof ListSchemaNode) {
+            final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
+            if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
+                final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).asMap();
+                isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
+            }
+        }
+    }
+
+    private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final MapEntryNode payload,
+            final List<QName> keyDefinitions) {
+        final Map<QName, Object> mutableCopyUriKeyValues = new HashMap<>(uriKeyValues);
+        for (final QName keyDefinition : keyDefinitions) {
+            final Object uriKeyValue = RestconfDocumentedException.throwIfNull(
+                    mutableCopyUriKeyValues.remove(keyDefinition), ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
+                    "Missing key %s in URI.", keyDefinition);
+
+            final Object dataKeyValue = payload.getIdentifier().getValue(keyDefinition);
+
+            if (!uriKeyValue.equals(dataKeyValue)) {
+                final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName()
+                        + "' specified in the URI doesn't match the value '" + dataKeyValue
+                        + "' specified in the message body. ";
+                throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+            }
+        }
+    }
+
     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
         return mountPoint.getService(DOMSchemaService.class)
             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))