Add some UT codes
[holmes/rule-management.git] / rulemgt / src / main / java / org / onap / holmes / rulemgt / dcae / DcaeConfigurationPolling.java
1 /**
2  * Copyright 2017 ZTE Corporation.
3  * <p>
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * <p>
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * <p>
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.holmes.rulemgt.dcae;
15
16 import com.alibaba.fastjson.JSON;
17 import com.google.gson.Gson;
18 import com.google.gson.GsonBuilder;
19 import com.google.gson.JsonDeserializationContext;
20 import com.google.gson.JsonDeserializer;
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonParseException;
23 import com.google.gson.reflect.TypeToken;
24
25 import java.io.IOException;
26 import java.io.UnsupportedEncodingException;
27 import java.lang.reflect.Type;
28 import java.util.HashMap;
29 import java.util.List;
30 import javax.ws.rs.core.MediaType;
31
32 import lombok.extern.slf4j.Slf4j;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.client.methods.HttpDelete;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPut;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.CloseableHttpClient;
39 import org.onap.holmes.common.dcae.DcaeConfigurationQuery;
40 import org.onap.holmes.common.dcae.entity.DcaeConfigurations;
41 import org.onap.holmes.common.dcae.entity.Rule;
42 import org.onap.holmes.common.exception.CorrelationException;
43 import org.onap.holmes.common.utils.GsonUtil;
44 import org.onap.holmes.common.utils.HttpsUtils;
45 import org.onap.holmes.common.utils.Md5Util;
46 import org.onap.holmes.rulemgt.bean.request.RuleCreateRequest;
47 import org.onap.holmes.rulemgt.bean.response.RuleQueryListResponse;
48 import org.onap.holmes.rulemgt.bean.response.RuleResult4API;
49
50 @Slf4j
51 public class DcaeConfigurationPolling implements Runnable {
52
53     public static final long POLLING_PERIOD = 30 * 1000L;
54
55     private String hostname;
56
57     private String url = "https://127.0.0.1:9101/api/holmes-rule-mgmt/v1/rule";
58
59     public DcaeConfigurationPolling(String hostname) {
60         this.hostname = hostname;
61     }
62
63     private String prevConfigMd5 = Md5Util.md5(null);
64
65     private boolean prevResult = false;
66
67     @Override
68     public void run() {
69         DcaeConfigurations dcaeConfigurations = null;
70         try {
71             dcaeConfigurations = DcaeConfigurationQuery.getDcaeConfigurations(hostname);
72             String md5 = Md5Util.md5(dcaeConfigurations);
73             if (prevResult && prevConfigMd5.equals(md5)) {
74                 log.info("Operation aborted due to identical configurations.");
75                 return;
76             }
77             prevConfigMd5 = md5;
78             prevResult = false;
79         } catch (CorrelationException e) {
80             log.error("Failed to fetch DCAE configurations. " + e.getMessage(), e);
81         } catch (Exception e) {
82             log.info("Failed to generate the MD5 information for new configurations.", e);
83         }
84         RuleQueryListResponse ruleQueryListResponse = null;
85         if (dcaeConfigurations != null) {
86             try {
87                 ruleQueryListResponse = getAllCorrelationRules();
88             } catch (CorrelationException e) {
89                 log.error("Failed to get right response!" + e.getMessage(), e);
90             } catch (IOException e) {
91                 log.error("Failed to extract response entity. " + e.getMessage(), e);
92             } catch (Exception e) {
93                 log.error("Failed to build http client. " + e.getMessage(), e);
94             }
95         }
96         if (ruleQueryListResponse != null) {
97             List<RuleResult4API> ruleResult4APIs = ruleQueryListResponse.getCorrelationRules();
98             deleteAllCorrelationRules(ruleResult4APIs);
99             try {
100                 prevResult = addAllCorrelationRules(dcaeConfigurations);
101             } catch (CorrelationException e) {
102                 log.error("Failed to add rules. " + e.getMessage(), e);
103                 prevResult = false;
104             }
105         }
106     }
107
108     public RuleQueryListResponse getAllCorrelationRules() throws CorrelationException, IOException {
109         HashMap<String, String> headers = new HashMap<>();
110         headers.put("Content-Type", MediaType.APPLICATION_JSON);
111         CloseableHttpClient httpClient = null;
112         HttpGet httpGet = new HttpGet(url);
113         try {
114             httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
115             HttpResponse httpResponse = HttpsUtils.get(httpGet, headers, httpClient);
116             String response = HttpsUtils.extractResponseEntity(httpResponse);
117             return JSON.parseObject(response, RuleQueryListResponse.class);
118         } finally {
119             httpGet.releaseConnection();
120             closeHttpClient(httpClient);
121         }
122     }
123
124     private boolean addAllCorrelationRules(DcaeConfigurations dcaeConfigurations) throws CorrelationException {
125         boolean suc = false;
126         for (Rule rule : dcaeConfigurations.getDefaultRules()) {
127             RuleCreateRequest ruleCreateRequest = getRuleCreateRequest(rule);
128             String content = "";
129             try {
130                 content = GsonUtil.beanToJson(ruleCreateRequest);
131             } catch (Exception e) {
132                 throw new CorrelationException("Failed to convert the message object to a json string.", e);
133             }
134             HashMap<String, String> headers = new HashMap<>();
135             headers.put("Content-Type", MediaType.APPLICATION_JSON);
136             headers.put("Accept", MediaType.APPLICATION_JSON);
137             HttpResponse httpResponse;
138             CloseableHttpClient httpClient = null;
139             HttpPut httpPut = new HttpPut(url);
140             try {
141                 httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
142                 httpResponse = HttpsUtils
143                         .put(httpPut, headers, new HashMap<>(), new StringEntity(content), httpClient);
144             } catch (UnsupportedEncodingException e) {
145                 throw new CorrelationException("Failed to create https entity.", e);
146             } catch (Exception e) {
147                 throw new CorrelationException(e.getMessage());
148             } finally {
149                 httpPut.releaseConnection();
150                 closeHttpClient(httpClient);
151             }
152             if (httpResponse != null) {
153                 suc = httpResponse.getStatusLine().getStatusCode() == 200;
154             }
155             if (!suc) {
156                 break;
157             }
158         }
159         return suc;
160     }
161
162     private void deleteAllCorrelationRules(List<RuleResult4API> ruleResult4APIs) {
163         ruleResult4APIs.forEach(correlationRule -> {
164             HashMap<String, String> headers = new HashMap<>();
165             headers.put("Content-Type", MediaType.APPLICATION_JSON);
166             CloseableHttpClient httpClient = null;
167             HttpDelete httpDelete = new HttpDelete(url + "/" + correlationRule.getRuleId());
168             try {
169                 httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
170                 HttpsUtils.delete(httpDelete, headers, httpClient);
171             } catch (Exception e) {
172                 log.warn("Failed to delete rule, the rule id is : " + correlationRule.getRuleId()
173                         + " exception messge is : " + e.getMessage(), e);
174             } finally {
175                 httpDelete.releaseConnection();
176                 closeHttpClient(httpClient);
177             }
178         });
179     }
180
181     private RuleCreateRequest getRuleCreateRequest(Rule rule) {
182         RuleCreateRequest ruleCreateRequest = new RuleCreateRequest();
183         ruleCreateRequest.setLoopControlName(rule.getLoopControlName());
184         ruleCreateRequest.setRuleName(rule.getName());
185         ruleCreateRequest.setContent(rule.getContents());
186         ruleCreateRequest.setDescription("");
187         ruleCreateRequest.setEnabled(1);
188         return ruleCreateRequest;
189     }
190
191     private void closeHttpClient(CloseableHttpClient httpClient) {
192         if (httpClient != null) {
193             try {
194                 httpClient.close();
195             } catch (IOException e) {
196                 log.warn("Failed to close http client!");
197             }
198         }
199     }
200 }