Deprecate CheckedValue.orElseThrow(Supplier)
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / PrettyTree.java
1 /*
2  * Copyright (c) 2021 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.concepts;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import java.util.function.Supplier;
14 import org.eclipse.jdt.annotation.NonNull;
15
16 /**
17  * A capture of a tree-like construct, which can be formatted into a pretty-printed tree. The string can be acquired
18  * via {@link #get()}.
19  *
20  * <p>
21  * This concept is purposefully designed as an abstract class which defers its {@link #toString()} to {@link #get()}, as
22  * it allows convenient and light-weight use with logging:
23  *
24  * <pre>
25  *   <code>
26  *     PrettyTreeAware treeLike;
27  *     LOG.debug("Tree is {}", treeLike.prettyTree());
28  *   </code>
29  * </pre>
30  */
31 @Beta
32 public abstract class PrettyTree implements Supplier<String> {
33     @Override
34     public @NonNull String get() {
35         final StringBuilder sb = new StringBuilder();
36         appendTo(sb, 0);
37         return sb.toString();
38     }
39
40     @Override
41     public final @NonNull String toString() {
42         return get();
43     }
44
45     /**
46      * Format this object into specified {@link StringBuilder} starting at specified initial depth.
47      *
48      * @param sb Target {@link StringBuilder}
49      * @param depth Initial nesting depth
50      * @throws NullPointerException if {@code sb} is null
51      * @throws IllegalArgumentException if {@code depth} is negative
52      */
53     public abstract void appendTo(StringBuilder sb, int depth);
54
55     /**
56      * Append a number of spaces equivalent to specified tree nesting depth into the specified {@link StringBuilder}.
57      *
58      * @param sb Target {@link StringBuilder}
59      * @param depth Nesting depth
60      * @throws NullPointerException if {@code sb} is null
61      * @throws IllegalArgumentException if {@code depth} is negative
62      */
63     protected static final void appendIndent(final StringBuilder sb, final int depth) {
64         checkArgument(depth >= 0, "Invalid depth %s", depth);
65         PrettyTreeIndent.indent(sb, depth);
66     }
67 }