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