4b80edf6861c8267a787e8f8b14fcb226d7b051f
[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 javax.annotation.Nonnull;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
16 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
17
18 public final class DataSchemaContextTree {
19     private static final LoadingCache<SchemaContext, DataSchemaContextTree> TREES = CacheBuilder.newBuilder()
20             .weakKeys().weakValues().build(new CacheLoader<SchemaContext, DataSchemaContextTree>() {
21                 @Override
22                 public DataSchemaContextTree load(final SchemaContext key) throws Exception {
23                     return new DataSchemaContextTree(key);
24                 }
25             });
26
27     private final DataSchemaContextNode<?> root;
28
29     private DataSchemaContextTree(final SchemaContext ctx) {
30         root = DataSchemaContextNode.from(ctx);
31     }
32
33     @Nonnull public static DataSchemaContextTree from(@Nonnull final SchemaContext ctx) {
34         return TREES.getUnchecked(ctx);
35     }
36
37     public DataSchemaContextNode<?> getChild(final YangInstanceIdentifier path) {
38         DataSchemaContextNode<?> currentOp = root;
39         for (PathArgument arg : path.getPathArguments()) {
40             currentOp = currentOp.getChild(arg);
41         }
42         return currentOp;
43     }
44
45     public DataSchemaContextNode<?> getRoot() {
46         return root;
47     }
48 }