BUG-2470: implement InMemoryDataTree.toString()
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / DataTreeState.java
1 /*
2  * Copyright (c) 2014 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.impl.schema.tree;
9
10 import com.google.common.base.Objects;
11 import com.google.common.base.Preconditions;
12 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
13 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
14
15 /**
16  * Instances of this class hold the current state of a DataTree instance.
17  * The need for encapsulation stems from atomic updates, which potentially change
18  * multiple fields in one go.
19  */
20 final class DataTreeState {
21     private final LatestOperationHolder holder;
22     private final SchemaContext schemaContext;
23     private final TreeNode root;
24
25     private DataTreeState(final TreeNode root) {
26         this.root = Preconditions.checkNotNull(root);
27         holder = new LatestOperationHolder();
28         schemaContext = null;
29     }
30
31     private DataTreeState(final TreeNode root, final LatestOperationHolder holder, final SchemaContext schemaContext) {
32         // It should be impossible to instantiate a new root without a SchemaContext
33         this.schemaContext = Preconditions.checkNotNull(schemaContext);
34         this.holder = Preconditions.checkNotNull(holder);
35         this.root = Preconditions.checkNotNull(root);
36     }
37
38     static DataTreeState createInitial(final TreeNode root) {
39         return new DataTreeState(root);
40     }
41
42     TreeNode getRoot() {
43         return root;
44     }
45
46     InMemoryDataTreeSnapshot newSnapshot() {
47         return new InMemoryDataTreeSnapshot(schemaContext, root, holder.newSnapshot());
48     }
49
50     DataTreeState withSchemaContext(final SchemaContext newSchemaContext, final SchemaAwareApplyOperation operation) {
51         holder.setCurrent(operation);
52         return new DataTreeState(root, holder, newSchemaContext);
53     }
54
55     DataTreeState withRoot(final TreeNode newRoot) {
56         return new DataTreeState(newRoot, holder, schemaContext);
57     }
58
59     @Override
60     public String toString() {
61         final TreeNode r = root;
62         return Objects.toStringHelper(this).add("data", StoreUtils.toStringTree(r.getData())).toString();
63     }
64 }