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