db2ea28e33a77e3f028ef5016ef03e70d1c927ba
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / DataSchemaContextTree.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.util;
9
10 import com.google.common.cache.CacheBuilder;
11 import com.google.common.cache.CacheLoader;
12 import com.google.common.cache.LoadingCache;
13 import java.util.Optional;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
17 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
18
19 /**
20  * Semantic tree binding a {@link SchemaContext} to a {@link NormalizedNode} tree. Since the layout of the schema
21  * and data has differences, the mapping is not trivial -- which is where this class comes in.
22  *
23  * @author Robert Varga
24  */
25 // FIXME: 6.0.0: @NonNullByDefault
26 public final class DataSchemaContextTree {
27     private static final LoadingCache<SchemaContext, DataSchemaContextTree> TREES = CacheBuilder.newBuilder()
28             .weakKeys().weakValues().build(new CacheLoader<SchemaContext, DataSchemaContextTree>() {
29                 @Override
30                 public DataSchemaContextTree load(final SchemaContext key) throws Exception {
31                     return new DataSchemaContextTree(key);
32                 }
33             });
34
35     private final DataSchemaContextNode<?> root;
36
37     private DataSchemaContextTree(final SchemaContext ctx) {
38         root = DataSchemaContextNode.from(ctx);
39     }
40
41     public static @NonNull DataSchemaContextTree from(final @NonNull SchemaContext ctx) {
42         return TREES.getUnchecked(ctx);
43     }
44
45     /**
46      * Find a child node as identified by an absolute {@link YangInstanceIdentifier}.
47      *
48      * @param path Path towards the child node
49      * @return Child node if present, or empty when corresponding child is not found.
50      * @throws NullPointerException if {@code path} is null
51      */
52     public @NonNull Optional<@NonNull DataSchemaContextNode<?>> findChild(final @NonNull YangInstanceIdentifier path) {
53         return getRoot().findChild(path);
54     }
55
56     public DataSchemaContextNode<?> getRoot() {
57         return root;
58     }
59 }