Add Logs for Response
[holmes/rule-management.git] / rulemgt / src / main / java / org / openo / holmes / rulemgt / bolt / enginebolt / EngineService.java
1 /**\r
2  * Copyright 2017 ZTE Corporation.\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 package org.openo.holmes.rulemgt.bolt.enginebolt;\r
17 \r
18 import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;\r
19 \r
20 import com.fasterxml.jackson.databind.ObjectMapper;\r
21 import java.io.ByteArrayOutputStream;\r
22 import java.io.IOException;\r
23 import java.io.InputStream;\r
24 import java.io.InputStreamReader;\r
25 import java.io.Reader;\r
26 import java.io.UnsupportedEncodingException;\r
27 import java.nio.charset.Charset;\r
28 import lombok.extern.slf4j.Slf4j;\r
29 import org.apache.commons.lang3.StringUtils;\r
30 import org.apache.http.ConnectionClosedException;\r
31 import org.apache.http.HttpEntity;\r
32 import org.apache.http.HttpResponse;\r
33 import org.apache.http.client.methods.HttpDelete;\r
34 import org.apache.http.client.methods.HttpGet;\r
35 import org.apache.http.client.methods.HttpPost;\r
36 import org.apache.http.client.methods.HttpPut;\r
37 import org.apache.http.client.methods.HttpRequestBase;\r
38 import org.apache.http.entity.BufferedHttpEntity;\r
39 import org.apache.http.entity.ByteArrayEntity;\r
40 import org.apache.http.entity.ContentType;\r
41 import org.apache.http.impl.client.CloseableHttpClient;\r
42 import org.apache.http.impl.client.HttpClients;\r
43 import org.apache.http.protocol.HTTP;\r
44 import org.apache.http.util.EntityUtils;\r
45 import org.jvnet.hk2.annotations.Service;\r
46 import org.openo.holmes.common.config.MicroServiceConfig;\r
47 import org.openo.holmes.common.exception.CorrelationException;\r
48 import org.openo.holmes.common.utils.I18nProxy;\r
49 import org.openo.holmes.rulemgt.bean.request.CorrelationCheckRule4Engine;\r
50 import org.openo.holmes.rulemgt.bean.request.CorrelationDeployRule4Engine;\r
51 import org.openo.holmes.rulemgt.constant.RuleMgtConstant;\r
52 \r
53 @Slf4j\r
54 @Service\r
55 public class EngineService {\r
56 \r
57     String url = "http://10.250.0.3:9102";\r
58 \r
59     protected HttpResponse delete(String packageName) throws IOException {\r
60         return deleteRequest(url + RuleMgtConstant.ENGINE_PATH + "/" + packageName);\r
61     }\r
62 \r
63     protected HttpResponse check(CorrelationCheckRule4Engine correlationCheckRule4Engine)\r
64             throws IOException {\r
65         ObjectMapper mapper = new ObjectMapper();\r
66         String content = mapper.writeValueAsString(correlationCheckRule4Engine);\r
67         String queryUrl = MicroServiceConfig.getMsbServerAddr()\r
68                 + "/openoapi/microservices/v1/services/holmes-engine/version/v1";\r
69         HttpGet httpGet = new HttpGet(queryUrl);\r
70         CloseableHttpClient httpClient = HttpClients.createDefault();\r
71         try {\r
72             HttpResponse httpResponse = httpClient.execute(httpGet);\r
73             log.info("response entity:" + EntityUtils.toString(httpResponse.getEntity()));\r
74         } finally {\r
75             httpClient.close();\r
76         }\r
77         return postRequest(url + RuleMgtConstant.ENGINE_PATH, content);\r
78     }\r
79 \r
80     protected HttpResponse deploy(CorrelationDeployRule4Engine correlationDeployRule4Engine) throws IOException {\r
81         ObjectMapper mapper = new ObjectMapper();\r
82         String content = mapper.writeValueAsString(correlationDeployRule4Engine);\r
83         return putRequest(url + RuleMgtConstant.ENGINE_PATH, content);\r
84     }\r
85 \r
86     private HttpResponse postRequest(String url, String content) throws IOException {\r
87         CloseableHttpClient httpClient = HttpClients.createDefault();\r
88         try {\r
89             HttpPost httpPost = new HttpPost(url);\r
90             log.info("url:" + url + "," + "post:" + httpPost);\r
91             setHeader(httpPost);\r
92             if (StringUtils.isNotEmpty(content)) {\r
93                 httpPost.setEntity(new ByteArrayEntity(content.getBytes()));\r
94             }\r
95             return httpClient.execute(httpPost);\r
96         } finally {\r
97             httpClient.close();\r
98         }\r
99     }\r
100 \r
101     private HttpResponse putRequest(String url, String content) throws IOException {\r
102         CloseableHttpClient httpClient = HttpClients.createDefault();\r
103         try {\r
104             HttpPut httpPut = new HttpPut(url);\r
105             setHeader(httpPut);\r
106             if (StringUtils.isNotEmpty(content)) {\r
107                 httpPut.setEntity(new ByteArrayEntity(content.getBytes()));\r
108             }\r
109             HttpResponse response = httpClient.execute(httpPut);\r
110             log.info("Return value for put request is " + EntityUtils.toString(response.getEntity()) + ".");\r
111             return response;\r
112         } finally {\r
113             httpClient.close();\r
114         }\r
115     }\r
116 \r
117     private HttpResponse deleteRequest(String url) throws IOException {\r
118         CloseableHttpClient httpClient = HttpClients.createDefault();\r
119         try {\r
120             HttpDelete httpDelete = new HttpDelete(url);\r
121             setHeader(httpDelete);\r
122             return httpClient.execute(httpDelete);\r
123         } finally {\r
124             httpClient.close();\r
125         }\r
126     }\r
127 \r
128     private void setHeader(HttpRequestBase httpRequestBase) {\r
129         httpRequestBase.setHeader("Accept", "application/json");\r
130         httpRequestBase.setHeader("Content-Type", "application/json");\r
131     }\r
132 \r
133     public String getResponseContent(HttpResponse response) {\r
134         HttpEntity entity = response.getEntity();\r
135         InputStream is = null;\r
136         if (entity != null) {\r
137             try {\r
138                 is = entity.getContent();\r
139                 final ContentType contentType = ContentType.getOrDefault(entity);\r
140                 Charset charset = contentType.getCharset();\r
141                 if (charset == null) {\r
142                     charset = HTTP.DEF_CONTENT_CHARSET;\r
143                 }\r
144                 final StringBuilder b = new StringBuilder();\r
145                 final char[] tmp = new char[1024];\r
146                 final Reader reader = new InputStreamReader(is, charset);\r
147                 try {\r
148                     int l;\r
149                     while ((l = reader.read(tmp)) != -1) {\r
150                         b.append(tmp, 0, l);\r
151                     }\r
152                 } catch (ConnectionClosedException ignore) {\r
153 \r
154                 } catch (IOException e) {\r
155                     log.info("Failed to read the contents of the input stream of the http entity.", e);\r
156                 }\r
157                 return b.toString();\r
158             } catch (IOException e) {\r
159                 log.info("Failed to read the contents of the http entity.", e);\r
160             } finally {\r
161                 try {\r
162                     if (is != null) {\r
163                         is.close();\r
164                     }\r
165                 } catch (IOException e) {\r
166                     log.info("Failed to close the input stream of the http entity.", e);\r
167                 }\r
168             }\r
169         }\r
170         return "{}";\r
171     }\r
172 \r
173     public byte[] getData(HttpEntity httpEntity) throws IOException {\r
174         log.info("Rule deployed. Package name: " + httpEntity.getContent().toString()\r
175                 + ". Content length: " + httpEntity.getContentLength());\r
176         BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);\r
177         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\r
178         bufferedHttpEntity.writeTo(byteArrayOutputStream);\r
179         byte[] responseBytes = byteArrayOutputStream.toByteArray();\r
180         return responseBytes;\r
181     }\r
182 \r
183 //    public String getResponseContent(HttpResponse httpResponse) throws CorrelationException {\r
184 //        byte[] dataByte;\r
185 //        String result = null;\r
186 //        try {\r
187 //            HttpEntity httpEntity = httpResponse.getEntity();\r
188 //            if (httpEntity != null) {\r
189 //                byte[] responseBytes = getData(httpEntity);\r
190 //                dataByte = responseBytes;\r
191 //                result = bytesToString(dataByte);\r
192 //            }\r
193 //            return result;\r
194 //        } catch (Exception e) {\r
195 //            throw new CorrelationException(I18nProxy.RULE_MANAGEMENT_PARSE_DEPLOY_RESULT_ERROR, e);\r
196 //        }\r
197 //    }\r
198 \r
199     private String bytesToString(byte[] bytes) throws UnsupportedEncodingException {\r
200         if (bytes != null) {\r
201             String returnStr = new String(bytes, "utf-8");\r
202             returnStr = StringUtils.trim(returnStr);\r
203             return returnStr;\r
204         }\r
205         return null;\r
206     }\r
207 }\r