Improve NormalizedNode formatting capabilities
[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.concepts.PrettyTree;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19
20 /**
21  * Abstract base class for {@link NormalizedNode} implementations.
22  *
23  * @param <I> Identifier type
24  * @param <T> Implemented {@link NormalizedNode} specialization type
25  */
26 @Beta
27 public abstract class AbstractNormalizedNode<I extends PathArgument, T extends NormalizedNode>
28         extends AbstractIdentifiable<PathArgument, I> implements NormalizedNode, Immutable {
29     protected AbstractNormalizedNode(final I identifier) {
30         super(identifier);
31     }
32
33     @Override
34     public final PrettyTree prettyTree() {
35         return new NormalizedNodePrettyTree(this);
36     }
37
38     @Override
39     public final boolean equals(final Object obj) {
40         if (this == obj) {
41             return true;
42         }
43         final Class<T> clazz = implementedType();
44         if (!clazz.isInstance(obj)) {
45             return false;
46         }
47         final T other = clazz.cast(obj);
48         return getIdentifier().equals(other.getIdentifier()) && valueEquals(other);
49     }
50
51     @Override
52     public final int hashCode() {
53         return 31 * getIdentifier().hashCode() + valueHashCode();
54     }
55
56     @Override
57     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
58         return super.addToStringAttributes(toStringHelper).add("body", body());
59     }
60
61     protected abstract @NonNull Class<T> implementedType();
62
63     protected abstract int valueHashCode();
64
65     protected abstract boolean valueEquals(@NonNull T other);
66 }