39f04d67c66647bb0ab4b719ebcad54da96a845e
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.vendorsoftwareproduct.utils;
18
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.Map;
22 import java.util.Set;
23
24 public class ComponentDependencyTracker {
25   private final Map<String, Set<String>> store = new HashMap<>();
26
27   /**
28    * Add dependency.
29    *
30    * @param dependent the dependent
31    * @param dependsOn the depends on
32    */
33   public void addDependency(String dependent, String dependsOn) {
34     if (dependent != null && dependsOn != null && dependent.trim().length() > 0 && dependsOn.trim()
35         .length() > 0) {
36       Set<String> dependsOnList = store
37               .computeIfAbsent(dependent.toLowerCase(), k -> new HashSet<>());
38       dependsOnList.add(dependsOn.toLowerCase());
39     }
40   }
41
42   /**
43    * Is cyclic dependency present boolean.
44    *
45    * @return the boolean
46    */
47   public boolean isCyclicDependencyPresent() {
48     Set<Map.Entry<String, Set<String>>> entries = store.entrySet();
49     for (Map.Entry<String, Set<String>> entry : entries) {
50       for (String dependentOn : entry.getValue()) {
51         if (!entry.getKey().equals(dependentOn) && isCyclicDependencyPresent(entry.getKey(),
52             dependentOn)) {
53           return true;
54         }
55       }
56     }
57     return false;
58   }
59
60   private boolean isCyclicDependencyPresent(String root, String dependentOn) {
61     Set<String> dependentOnList = store.get(dependentOn);
62     if (dependentOnList != null && dependentOnList.contains(root)) {
63       return true;
64     } else if (dependentOnList != null) {
65       for (String item : dependentOnList) {
66         return isCyclicDependencyPresent(root, item);
67       }
68     }
69     return false;
70   }
71
72 }