Populate data/ hierarchy
[yangtools.git] / yang / yang-model-ri / src / main / java / org / opendaylight / yangtools / yang / model / ri / stmt / impl / eff / AbstractKeyEffectiveStatement.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.model.ri.stmt.impl.eff;
9
10 import static com.google.common.base.Verify.verify;
11
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Set;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
17 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
18 import org.opendaylight.yangtools.yang.model.spi.meta.AbstractDeclaredEffectiveStatement;
19
20 abstract class AbstractKeyEffectiveStatement
21         extends AbstractDeclaredEffectiveStatement.Default<Set<QName>, KeyStatement>
22         implements KeyEffectiveStatement {
23     abstract static class Foreign extends AbstractKeyEffectiveStatement {
24         // Polymorphic, with single value or a collection
25         private final Object argument;
26
27         Foreign(final KeyStatement declared, final Set<QName> argument) {
28             super(declared);
29             this.argument = maskSet(argument);
30         }
31
32         @Override
33         public final Set<QName> argument() {
34             return unmaskSet(argument);
35         }
36
37         private static @NonNull Object maskSet(final @NonNull Set<QName> set) {
38             return set.size() == 1 ? set.iterator().next() : set;
39         }
40
41         @SuppressWarnings("unchecked")
42         private static @NonNull Set<QName> unmaskSet(final @NonNull Object masked) {
43             if (masked instanceof Set) {
44                 return (Set<QName>) masked;
45             }
46             verify(masked instanceof QName, "Unexpected argument %s", masked);
47             return ImmutableSet.of((QName) masked);
48         }
49     }
50
51     abstract static class Local extends AbstractKeyEffectiveStatement {
52         Local(final KeyStatement declared) {
53             super(declared);
54         }
55
56         @Override
57         public final Set<QName> argument() {
58             return getDeclared().argument();
59         }
60     }
61
62     AbstractKeyEffectiveStatement(final KeyStatement declared) {
63         super(declared);
64     }
65 }