Add UniqueValidation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / UniqueValidator.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.MoreObjects;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Maps;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Optional;
24 import java.util.Set;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.yangtools.concepts.Immutable;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
30 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * A validator for a single {@code unique} constraint. This class is further specialized for single- and
38  * multiple-constraint implementations.
39  *
40  * <p>
41  * The basic idea is that for each list entry there is a corresponding value vector of one or more values, each
42  * corresponding to one component of the {@code unique} constraint.
43  */
44 abstract class UniqueValidator<T> implements Immutable {
45     private static final class One extends UniqueValidator<Object> {
46         One(final List<NodeIdentifier> path) {
47             super(encodePath(path));
48         }
49
50         @Override
51         Object extractValues(final Map<List<NodeIdentifier>, Object> valueCache, final DataContainerNode<?> data) {
52             return extractValue(valueCache, data, decodePath(descendants));
53         }
54
55         @Override
56         Map<Descendant, @Nullable Object> indexValues(final Object values) {
57             return Collections.singletonMap(decodeDescendant(descendants), values);
58         }
59     }
60
61     private static final class Many extends UniqueValidator<Set<Object>> {
62         Many(final List<List<NodeIdentifier>> descendantPaths) {
63             super(descendantPaths.stream().map(UniqueValidator::encodePath).collect(ImmutableSet.toImmutableSet()));
64         }
65
66         @Override
67         UniqueValues extractValues(final Map<List<NodeIdentifier>, Object> valueCache,
68                 final DataContainerNode<?> data) {
69             return descendants.stream()
70                 .map(obj -> extractValue(valueCache, data, decodePath(obj)))
71                 .collect(UniqueValues.COLLECTOR);
72         }
73
74         @Override
75         Map<Descendant, @Nullable Object> indexValues(final Object values) {
76             final Map<Descendant, @Nullable Object> index = Maps.newHashMapWithExpectedSize(descendants.size());
77             final Iterator<?> it = ((UniqueValues) values).iterator();
78             for (Object obj : descendants) {
79                 verify(index.put(decodeDescendant(obj), it.next()) == null);
80             }
81             return index;
82         }
83     }
84
85     private static final Logger LOG = LoggerFactory.getLogger(UniqueValidator.class);
86
87     final @NonNull T descendants;
88
89     UniqueValidator(final T descendants) {
90         this.descendants = requireNonNull(descendants);
91     }
92
93     static UniqueValidator<?> of(final List<List<NodeIdentifier>> descendants) {
94         return descendants.size() == 1 ? new One(descendants.get(0)) : new Many(descendants);
95     }
96
97     /**
98      * Extract a value vector from a particular child.
99      *
100      * @param valueCache Cache of descendants already looked up
101      * @param data Root data node
102      * @return Value vector
103      */
104     abstract @Nullable Object extractValues(Map<List<NodeIdentifier>, Object> valueCache,
105         DataContainerNode<?> data);
106
107     /**
108      * Index a value vector by associating each value with its corresponding {@link Descendant}.
109      *
110      * @param values Value vector
111      * @return Map of Descandant/value relations
112      */
113     abstract Map<Descendant, @Nullable Object> indexValues(Object values);
114
115     /**
116      * Encode a path for storage. Single-element paths are squashed to their only element. The inverse operation is
117      * {@link #decodePath(Object)}.
118      *
119      * @param path Path to encode
120      * @return Encoded path.
121      */
122     static final Object encodePath(final List<NodeIdentifier> path) {
123         return path.size() == 1 ? path.get(0) : ImmutableList.copyOf(path);
124     }
125
126     /**
127      * Decode a path from storage. This is the inverse operation to {@link #encodePath(List)}.
128      *
129      * @param obj Encoded path
130      * @return Decoded path
131      */
132     static final @NonNull ImmutableList<NodeIdentifier> decodePath(final Object obj) {
133         return obj instanceof NodeIdentifier ? ImmutableList.of((NodeIdentifier) obj)
134             : (ImmutableList<NodeIdentifier>) obj;
135     }
136
137     static final @NonNull Descendant decodeDescendant(final Object obj) {
138         return Descendant.of(Collections2.transform(decodePath(obj), NodeIdentifier::getNodeType));
139     }
140
141     /**
142      * Extract the value for a single descendant.
143      *
144      * @param valueCache Cache of descendants already looked up
145      * @param data Root data node
146      * @param path Descendant path
147      * @return Value for the descendant
148      */
149     static final @Nullable Object extractValue(final Map<List<NodeIdentifier>, Object> valueCache,
150             final DataContainerNode<?> data, final List<NodeIdentifier> path) {
151         return valueCache.computeIfAbsent(path, key -> extractValue(data, key));
152     }
153
154     /**
155      * Extract the value for a single descendant.
156      *
157      * @param data Root data node
158      * @param path Descendant path
159      * @return Value for the descendant
160      */
161     private static @Nullable Object extractValue(final DataContainerNode<?> data, final List<NodeIdentifier> path) {
162         DataContainerNode<?> current = data;
163         final Iterator<NodeIdentifier> it = path.iterator();
164         while (true) {
165             final NodeIdentifier step = it.next();
166             final Optional<DataContainerChild<?, ?>> optNext = current.getChild(step);
167             if (optNext.isEmpty()) {
168                 return null;
169             }
170
171             final DataContainerChild<?, ?> next = optNext.orElseThrow();
172             if (!it.hasNext()) {
173                 checkState(next instanceof LeafNode, "Unexpected node %s at %s", next, path);
174                 final Object value = next.getValue();
175                 LOG.trace("Resolved {} to value {}", path, value);
176                 return value;
177             }
178
179             checkState(next instanceof DataContainerNode, "Unexpected node %s in %s", next, path);
180             current = (DataContainerNode<?>) next;
181         }
182     }
183
184     @Override
185     public final String toString() {
186         return MoreObjects.toStringHelper(this).add("paths", descendants).toString();
187     }
188 }