Use Optional.isEmpty()
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / utils / parser / ParserIdentifier.java
index cadc7854fb9cba1c5d1c4116bdca8ae64721e500..305b93ff7a95829daa5c8f34ea992eee13158842 100644 (file)
@@ -7,6 +7,10 @@
  */
 package org.opendaylight.restconf.nb.rfc8040.utils.parser;
 
+import static com.google.common.base.Preconditions.checkState;
+import static com.google.common.base.Verify.verifyNotNull;
+
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Iterables;
 import java.time.format.DateTimeParseException;
@@ -14,10 +18,13 @@ import java.util.AbstractMap.SimpleImmutableEntry;
 import java.util.Date;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map.Entry;
 import java.util.Optional;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
@@ -25,12 +32,15 @@ import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
 import org.opendaylight.restconf.common.schema.SchemaExportContext;
 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
-import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
 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.util.DataSchemaContextNode;
 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
+import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
+import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -44,6 +54,7 @@ import org.slf4j.LoggerFactory;
 public final class ParserIdentifier {
 
     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
+    private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
 
     private ParserIdentifier() {
         throw new UnsupportedOperationException("Util class.");
@@ -68,69 +79,88 @@ public final class ParserIdentifier {
      *           - mount point service
      * @return {@link InstanceIdentifierContext}
      */
-    public static InstanceIdentifierContext<?> toInstanceIdentifier(
-            final String identifier,
-            final SchemaContext schemaContext,
-            final Optional<DOMMountPointService> mountPointService) {
-        if (identifier != null && identifier.contains(RestconfConstants.MOUNT)) {
-            if (!mountPointService.isPresent()) {
-                throw new RestconfDocumentedException("Mount point service is not available");
-            }
+    public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
+            final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
+        if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
+            return createIIdContext(schemaContext, identifier, null);
+        }
+        if (mountPointService.isEmpty()) {
+            throw new RestconfDocumentedException("Mount point service is not available");
+        }
 
-            final Iterator<String> pathsIt = Splitter.on("/" + RestconfConstants.MOUNT).split(identifier).iterator();
+        final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
+        final String mountPointId = pathsIt.next();
+        final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
+        final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
+                .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
+                    ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED_TRANSPORT));
 
-            final String mountPointId = pathsIt.next();
-            final YangInstanceIdentifier mountYangInstanceIdentifier = IdentifierCodec.deserialize(
-                    mountPointId, schemaContext);
-            final Optional<DOMMountPoint> mountPoint =
-                    mountPointService.get().getMountPoint(mountYangInstanceIdentifier);
+        final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
+        final String pathId = pathsIt.next().replaceFirst("/", "");
+        return createIIdContext(mountSchemaContext, pathId, mountPoint);
+    }
 
-            if (!mountPoint.isPresent()) {
-                throw new RestconfDocumentedException(
-                        "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
-            }
+    /**
+     * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
+     * and {@link SchemaContext}, {@link DOMMountPoint}.
+     *
+     * @param url Invocation URL
+     * @param schemaContext SchemaContext in which the path is to be interpreted in
+     * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
+     * @return {@link InstanceIdentifierContext}
+     * @throws RestconfDocumentedException if the path cannot be resolved
+     */
+    private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
+            final String url, final @Nullable DOMMountPoint mountPoint) {
+        final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
+        return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
+                schemaContext);
+    }
 
-            final DOMMountPoint domMountPoint = mountPoint.get();
-            final SchemaContext mountSchemaContext = domMountPoint.getSchemaContext();
+    private static SchemaNode getPathSchema(final EffectiveModelContext schemaContext,
+            final YangInstanceIdentifier urlPath) {
+        // First things first: an empty path means data invocation on SchemaContext
+        if (urlPath.isEmpty()) {
+            return schemaContext;
+        }
 
-            final String pathId = pathsIt.next().replaceFirst("/", "");
-            final YangInstanceIdentifier pathYangInstanceIdentifier = IdentifierCodec.deserialize(
-                    pathId, mountSchemaContext);
+        // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
+        final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
+                .findChild(verifyNotNull(urlPath.getParent()))
+                .orElseThrow(
+                    // Parent data node is not present, this is not a valid location.
+                    () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
 
-            final DataSchemaContextNode<?> child = DataSchemaContextTree.from(mountSchemaContext)
-                .getChild(pathYangInstanceIdentifier);
-            if (child != null) {
-                return new InstanceIdentifierContext<SchemaNode>(pathYangInstanceIdentifier, child.getDataSchemaNode(),
-                        domMountPoint, mountSchemaContext);
-            }
-            final QName rpcQName = pathYangInstanceIdentifier.getLastPathArgument().getNodeType();
-            RpcDefinition def = null;
-            for (final RpcDefinition rpcDefinition : mountSchemaContext
-                    .findModule(rpcQName.getModule()).get().getRpcs()) {
-                if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
-                    def = rpcDefinition;
-                    break;
-                }
-            }
-            return new InstanceIdentifierContext<>(pathYangInstanceIdentifier, def, domMountPoint, mountSchemaContext);
-        } else {
-            final YangInstanceIdentifier deserialize = IdentifierCodec.deserialize(identifier, schemaContext);
-            final DataSchemaContextNode<?> child = DataSchemaContextTree.from(schemaContext).getChild(deserialize);
+        // Now try to resolve the last component as a data item...
+        final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
+        if (data != null) {
+            return data.getDataSchemaNode();
+        }
 
-            if (child != null) {
-                return new InstanceIdentifierContext<SchemaNode>(
-                            deserialize, child.getDataSchemaNode(), null, schemaContext);
+        // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
+        // actions can reside everywhere else (and SchemaContext reports them empty)
+        final QName qname = urlPath.getLastPathArgument().getNodeType();
+        final DataSchemaNode parentSchema = parent.getDataSchemaNode();
+        if (parentSchema instanceof SchemaContext) {
+            for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
+                if (qname.equals(rpc.getQName())) {
+                    return rpc;
+                }
             }
-            final QName rpcQName = deserialize.getLastPathArgument().getNodeType();
-            RpcDefinition def = null;
-            for (final RpcDefinition rpcDefinition : schemaContext.findModule(rpcQName.getModule()).get().getRpcs()) {
-                if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
-                    def = rpcDefinition;
-                    break;
+        }
+        if (parentSchema instanceof ActionNodeContainer) {
+            for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
+                if (qname.equals(action.getQName())) {
+                    return action;
                 }
             }
-            return new InstanceIdentifierContext<>(deserialize, def, null, schemaContext);
         }
+
+        // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
+        //          is deemed invalid
+        throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
+            ErrorTag.INVALID_VALUE);
     }
 
     /**
@@ -141,7 +171,7 @@ public final class ParserIdentifier {
      * @return                      Yang instance identifier serialized to String
      */
     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
-            final SchemaContext schemaContext) {
+            final EffectiveModelContext schemaContext) {
         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
     }
 
@@ -154,8 +184,7 @@ public final class ParserIdentifier {
      */
     public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
         // check if more than one slash is not used as path separator
-        if (identifier.contains(
-                String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
+        if (identifier.contains("//")) {
             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
             throw new RestconfDocumentedException(
                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
@@ -166,7 +195,7 @@ public final class ParserIdentifier {
         final String moduleNameAndRevision;
         if (mountIndex >= 0) {
             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
-                    .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
+                    .replaceFirst("/", "");
         } else {
             moduleNameAndRevision = identifier;
         }
@@ -197,21 +226,21 @@ public final class ParserIdentifier {
      * {@link SchemaExportContext}.
      *
      * @param schemaContext
-     *             {@link SchemaContext}
+     *             {@link EffectiveModelContext}
      * @param identifier
      *             path parameter
      * @param domMountPointService
      *             {@link DOMMountPointService}
      * @return {@link SchemaExportContext}
      */
-    public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
+    public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
             final String identifier, final DOMMountPointService domMountPointService,
             final DOMYangTextSourceProvider sourceProvider) {
         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
         final Iterator<String> componentIter = pathComponents.iterator();
         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
-            final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
-            final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
+            final String moduleName = validateAndGetModulName(componentIter);
+            final Revision revision = validateAndGetRevision(componentIter);
             final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
             return new SchemaExportContext(schemaContext, module, sourceProvider);
         } else {
@@ -231,13 +260,66 @@ public final class ParserIdentifier {
 
                 pathBuilder.append(current);
             }
-            final InstanceIdentifierContext<?> point = ParserIdentifier
-                    .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
-            final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
-            final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
-            final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
-                    .orElse(null);
-            return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
+            final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
+                Optional.of(domMountPointService));
+            final String moduleName = validateAndGetModulName(componentIter);
+            final Revision revision = validateAndGetRevision(componentIter);
+            final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
+            final Module module = context.findModule(moduleName, revision).orElse(null);
+            return new SchemaExportContext(context, module, sourceProvider);
+        }
+    }
+
+    /**
+     * Validation and parsing of revision.
+     *
+     * @param revisionDate iterator
+     * @return A Revision
+     */
+    @VisibleForTesting
+    static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
+        RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
+            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        try {
+            return Revision.of(revisionDate.next());
+        } catch (final DateTimeParseException e) {
+            throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
         }
     }
+
+    /**
+     * Validation of name.
+     *
+     * @param moduleName iterator
+     * @return {@link String}
+     */
+    @VisibleForTesting
+    static String validateAndGetModulName(final Iterator<String> moduleName) {
+        RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
+            ErrorTag.INVALID_VALUE);
+        final String name = moduleName.next();
+
+        RestconfDocumentedException.throwIf(
+            name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
+            "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
+            "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        RestconfDocumentedException.throwIf(
+            !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
+            "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+
+        return name;
+    }
+
+    private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
+        final EffectiveModelContext context = modelContext(mountPoint);
+        checkState(context != null, "Mount point %s does not have a model context", mountPoint);
+        return context;
+    }
+
+    private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
+        return mountPoint.getService(DOMSchemaService.class)
+            .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
+            .orElse(null);
+    }
 }