Split out yang-data-spi
[yangtools.git] / data / yang-data-spi / src / main / java / org / opendaylight / yangtools / yang / data / spi / node / AbstractNormalizedNode.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2020 PANTHEON.tech, s.r.o
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.yangtools.yang.data.spi.node;
10
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import org.eclipse.jdt.annotation.NonNull;
14 import org.opendaylight.yangtools.concepts.AbstractIdentifiable;
15 import org.opendaylight.yangtools.concepts.Immutable;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18
19 /**
20  * Abstract base class for {@link NormalizedNode} implementations.
21  *
22  * @param <I> Identifier type
23  * @param <T> Implemented {@link NormalizedNode} specialization type
24  */
25 @Beta
26 public abstract class AbstractNormalizedNode<I extends PathArgument, T extends NormalizedNode>
27         extends AbstractIdentifiable<PathArgument, I> implements NormalizedNode, Immutable {
28     protected AbstractNormalizedNode(final I identifier) {
29         super(identifier);
30     }
31
32     @Override
33     public final boolean equals(final Object obj) {
34         if (this == obj) {
35             return true;
36         }
37         final Class<T> clazz = implementedType();
38         if (!clazz.isInstance(obj)) {
39             return false;
40         }
41         final T other = clazz.cast(obj);
42         return getIdentifier().equals(other.getIdentifier()) && valueEquals(other);
43     }
44
45     @Override
46     public final int hashCode() {
47         return 31 * getIdentifier().hashCode() + valueHashCode();
48     }
49
50     @Override
51     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
52         return super.addToStringAttributes(toStringHelper).add("body", body());
53     }
54
55     protected abstract @NonNull Class<T> implementedType();
56
57     protected abstract int valueHashCode();
58
59     protected abstract boolean valueEquals(@NonNull T other);
60 }