Implant vid-app-common org.onap.vid.job (main and test)
[vid.git] / vid-app-common / src / main / java / org / onap / vid / utils / Tree.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.utils
22
23 data class Node<T>(val value:T, val children:MutableMap<T, Node<T>> = hashMapOf())
24
25 data class Tree<T>(private val root:Node<T>) {
26
27     constructor(value: T) : this(Node(value))
28
29     fun getRootValue():T {
30         return root.value;
31     }
32
33     fun addPath(vararg path: T) {
34         addPath(path.asList())
35     }
36
37     fun addPath(path:Collection<T>) {
38         var currentNode = root
39         path.forEach {
40             currentNode = currentNode.children.getOrPut(it) {Node(it)}
41         }
42     }
43
44     fun getChildrenDepth(): Int {
45         return getMaxDepth(root) - 1
46     }
47
48     private fun getMaxDepth(level:Node<T>): Int {
49         return (level.children.map{getMaxDepth(it.value)}.max() ?: 0) + 1
50     }
51
52     fun getSubTree(vararg path: T): Tree<T>? {
53         return getSubTree(path.asList())
54     }
55
56     fun getSubTree(path:Collection<T>): Tree<T>? {
57         var currentNode:Node<T> = root
58         path.forEach {
59             currentNode = currentNode.children[it] ?: return null
60         }
61         return Tree(currentNode)
62     }
63
64     fun isPathExist(vararg path: T): Boolean {
65         return isPathExist(path.asList())
66     }
67
68     fun isPathExist(path:Collection<T>): Boolean {
69         return getSubTree(path)!=null
70     }
71 }
72