BUG-4355: mandatory node presence enforcement
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / CaseEnforcer.java
1 /*
2  * Copyright (c) 2015 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.yangtools.yang.data.impl.schema.tree;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableMap.Builder;
13 import java.util.Map;
14 import java.util.Map.Entry;
15 import java.util.Set;
16 import org.opendaylight.yangtools.concepts.Immutable;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
21 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23
24 final class CaseEnforcer implements Immutable {
25     private final Map<NodeIdentifier, DataSchemaNode> children;
26     private final MandatoryLeafEnforcer enforcer;
27
28     private CaseEnforcer(final Map<NodeIdentifier, DataSchemaNode> children, final MandatoryLeafEnforcer enforcer) {
29         this.children = Preconditions.checkNotNull(children);
30         this.enforcer = Preconditions.checkNotNull(enforcer);
31     }
32
33     static CaseEnforcer forTree(final ChoiceCaseNode schema, final TreeType type) {
34         final Builder<NodeIdentifier, DataSchemaNode> builder = ImmutableMap.builder();
35         if (SchemaAwareApplyOperation.belongsToTree(type, schema)) {
36             for (DataSchemaNode child : schema.getChildNodes()) {
37                 if (SchemaAwareApplyOperation.belongsToTree(type, child)) {
38                     builder.put(NodeIdentifier.create(child.getQName()), child);
39                 }
40             }
41         }
42
43         final Map<NodeIdentifier, DataSchemaNode> children = builder.build();
44         return children.isEmpty() ? null : new CaseEnforcer(children, MandatoryLeafEnforcer.forContainer(schema, type));
45     }
46
47     Set<Entry<NodeIdentifier, DataSchemaNode>> getChildEntries() {
48         return children.entrySet();
49     }
50
51     Set<NodeIdentifier> getChildIdentifiers() {
52         return children.keySet();
53     }
54
55     void enforceOnTreeNode(final TreeNode tree) {
56         enforcer.enforceOnTreeNode(tree);
57     }
58
59     void enforceOnTreeNode(final NormalizedNode<?, ?> normalizedNode) {
60         enforcer.enforceOnTreeNode(normalizedNode);
61     }
62 }