Fixed an Object Comparison Bug
[holmes/rule-management.git] / rulemgt / src / main / java / org / onap / holmes / rulemgt / tools / EngineTools.java
1 /**
2  * Copyright 2017-2020 ZTE Corporation.
3  * <p>
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  * <p>
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * <p>
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.onap.holmes.rulemgt.tools;
18
19 import lombok.extern.slf4j.Slf4j;
20 import org.jvnet.hk2.annotations.Service;
21 import org.onap.holmes.common.api.entity.CorrelationRule;
22 import org.onap.holmes.common.engine.entity.EngineEntity;
23 import org.onap.holmes.common.engine.service.EngineEntityService;
24 import org.onap.holmes.rulemgt.wrapper.RuleQueryWrapper;
25
26 import javax.inject.Inject;
27 import java.util.Arrays;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.stream.Collectors;
31
32 @Service
33 @Slf4j
34 public class EngineTools {
35
36     @Inject
37     private RuleQueryWrapper ruleQueryWrapper;
38     @Inject
39     private EngineEntityService engineEntityService;
40
41     public List<String> getInstanceList() {
42         List<EngineEntity> entities = engineEntityService.getAllEntities();
43         return entities.stream().map(EngineEntity::getIp).collect(Collectors.toList());
44     }
45
46     public List<String> getLegacyEngineInstances() {
47         return engineEntityService.getLegacyEngines();
48     }
49
50     public String getEngineWithLeastRules() {
51         LinkedHashMap<String, Integer> ruleNumInEachEngine = new LinkedHashMap<>();
52
53         try {
54             for (String ip : getInstanceList()) {
55                 List<CorrelationRule> rules = ruleQueryWrapper.queryRuleByEngineInstance(ip);
56                 if (rules != null) {
57                     ruleNumInEachEngine.put(ip, rules.size());
58                 }
59             }
60         } catch (Exception e) {
61             log.error("getEngineWithLeastRules failed!" + e.getMessage());
62         }
63
64         Integer[] numOfRules = ruleNumInEachEngine.values().toArray(new Integer[0]);
65         Arrays.sort(numOfRules);
66
67         for (String ip : ruleNumInEachEngine.keySet()) {
68             if (ruleNumInEachEngine.get(ip).equals(numOfRules[0])) {
69                 return ip;
70             }
71         }
72         return null;
73     }
74 }