Add NormalizedNodeContainer.size()
[yangtools.git] / yang / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / schema / tree / spi / LazyContainerNode.java
1 /*
2  * Copyright (c) 2015 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.api.schema.tree.spi;
9
10 import com.google.common.base.MoreObjects.ToStringHelper;
11 import com.google.common.collect.Collections2;
12 import java.util.Map;
13 import java.util.Optional;
14 import org.opendaylight.yangtools.util.MapAdaptor;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17
18 /**
19  * Lazily-materialized container node. Any new/modified children are tracked in a map. This map is consulted before
20  * instantiating a child node from data node. Resulting node is not cached.
21  */
22 final class LazyContainerNode extends AbstractModifiedContainerNode {
23     LazyContainerNode(final NormalizedNode<?, ?> data, final Version version, final Version subtreeVersion) {
24         this(data, version, MapAdaptor.getDefaultInstance().initialSnapshot(1), subtreeVersion);
25     }
26
27     LazyContainerNode(final NormalizedNode<?, ?> data, final Version version,
28             final Map<PathArgument, TreeNode> children, final Version subtreeVersion) {
29         super(data, version, children, subtreeVersion);
30     }
31
32     @Override
33     public MutableTreeNode mutable() {
34         final Map<PathArgument, TreeNode> snapshot = snapshotChildren();
35         if (snapshot.size() == castData().size()) {
36             return new MaterializedMutableContainerNode(this, snapshot);
37         }
38
39         return new LazyMutableContainerNode(this, snapshot);
40     }
41
42     @Override
43     public Optional<TreeNode> getChild(final PathArgument childId) {
44         final TreeNode modified = getModifiedChild(childId);
45         return modified == null ? getChildFromData(childId) : Optional.of(modified);
46     }
47
48     @Override
49     protected ToStringHelper addToStringAttributes(final ToStringHelper helper) {
50         // Modified children add added by superclass. Here we filter the other children.
51         return super.addToStringAttributes(helper).add("untouched", Collections2.filter(castData().getValue(),
52             input -> getModifiedChild(input.getIdentifier()) == null));
53     }
54 }