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