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