Guard against empty YangInstanceIdentifier values
[yangtools.git] / data / yang-data-spi / src / main / java / org / opendaylight / yangtools / yang / data / spi / node / impl / AbstractImmutableNormalizedNodeBuilder.java
1 /*
2  * Copyright (c) 2013 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.spi.node.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import org.eclipse.jdt.annotation.NonNull;
13 import org.eclipse.jdt.annotation.Nullable;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
18
19 abstract class AbstractImmutableNormalizedNodeBuilder<I extends PathArgument, V, R extends NormalizedNode>
20         implements NormalizedNodeBuilder<I, V, R> {
21     private @Nullable I nodeIdentifier = null;
22     private @Nullable V value = null;
23
24     protected final I getNodeIdentifier() {
25         return checkSet(nodeIdentifier, "Identifier has not been set");
26     }
27
28     protected final V getValue() {
29         return checkSet(value, "Value has not been set");
30     }
31
32     @Override
33     public NormalizedNodeBuilder<I, V, R> withValue(final V withValue) {
34         this.value = checkValue(withValue);
35         return this;
36     }
37
38     @Override
39     public NormalizedNodeBuilder<I, V, R> withNodeIdentifier(final I withNodeIdentifier) {
40         this.nodeIdentifier = requireNonNull(withNodeIdentifier);
41         return this;
42     }
43
44     private static <T> @NonNull T checkSet(final @Nullable T obj, final String message) {
45         if (obj == null) {
46             throw new IllegalStateException(message);
47         }
48         return obj;
49     }
50
51     protected static final <T> @NonNull T checkValue(final @Nullable T value) {
52         final var nonNull = requireNonNull(value);
53         if (nonNull instanceof YangInstanceIdentifier yiid && yiid.isEmpty()) {
54             throw new IllegalArgumentException("Node value cannot be an empty instance identifier");
55         }
56         return nonNull;
57     }
58 }