Fixed the Policy API issues and Bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / elk / client / ElkConnectorImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.policy.pap.xacml.rest.elk.client;
21
22 import java.io.IOException;
23 import java.util.Map;
24 import java.util.Map.Entry;
25
26 import org.elasticsearch.index.query.QueryBuilders;
27 import org.elasticsearch.index.query.QueryStringQueryBuilder;
28 import org.elasticsearch.search.builder.SearchSourceBuilder;
29 import org.json.JSONObject;
30 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
31 import org.openecomp.policy.common.logging.flexlogger.Logger;
32 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
33 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
34
35 import io.searchbox.action.Action;
36 import io.searchbox.client.JestClient;
37 import io.searchbox.client.JestClientFactory;
38 import io.searchbox.client.JestResult;
39 import io.searchbox.client.config.HttpClientConfig;
40 import io.searchbox.core.Delete;
41 import io.searchbox.core.Index;
42 import io.searchbox.core.Search;
43 import io.searchbox.core.Search.Builder;
44 import io.searchbox.indices.IndicesExists;
45 import io.searchbox.indices.type.TypeExist;
46 import io.searchbox.params.Parameters;
47
48 public class ElkConnectorImpl implements ElkConnector{
49
50         private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class);
51
52         protected final JestClientFactory jestFactory = new JestClientFactory();
53         protected final JestClient jestClient;  
54         protected static int QUERY_MAXRECORDS = 1000;
55
56         public ElkConnectorImpl() {
57                 if (LOGGER.isDebugEnabled()){
58                         LOGGER.debug("ENTER: -");
59                 }
60                 HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
61                 jestFactory.setHttpClientConfig(jestClientConfig);
62                 jestClient = jestFactory.getObject();
63         }
64
65         protected boolean isType(PolicyIndexType type) throws IOException {
66                 if (LOGGER.isDebugEnabled()){
67                         LOGGER.debug("ENTER: -");
68                 }
69
70                 try {
71                         Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
72                         JestResult result = jestClient.execute(typeQuery);
73
74                         if (LOGGER.isInfoEnabled()) {
75                                 LOGGER.info("JSON:" + result.getJsonString());
76                                 LOGGER.info("ERROR:" + result.getErrorMessage());
77                                 LOGGER.info("PATH:" + result.getPathToResult());
78                                 LOGGER.info(result.getJsonObject());
79                         }
80                         return result.isSucceeded();    
81                 } catch (IOException e) {
82                         LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e);
83                         throw e;
84                 }
85         }
86
87         protected boolean isIndex() throws IOException {
88                 try {
89                         Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build();
90
91                         JestResult result = jestClient.execute(indexQuery);
92                         if (LOGGER.isInfoEnabled()) {
93                                 LOGGER.info("JSON:" + result.getJsonString());
94                                 LOGGER.info("ERROR:" + result.getErrorMessage());
95                                 LOGGER.info("PATH:" + result.getPathToResult());
96                                 LOGGER.info(result.getJsonObject());
97                         }
98                         return result.isSucceeded();    
99                 } catch (IOException e) {
100                         LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e);
101                         throw e;
102                 }
103         }
104
105         @Override
106         public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException {
107                 if (LOGGER.isTraceEnabled()){
108                         LOGGER.trace("ENTER: " + text);
109                 }
110
111                 if (text == null || text.isEmpty()) {
112                         throw new IllegalArgumentException("No search string provided");
113                 }
114
115                 QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*");
116                 SearchSourceBuilder searchSourceBuilder = 
117                                 new SearchSourceBuilder().query(mQ);
118                 
119                 Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).
120                                 addIndex(ELK_INDEX_POLICY).
121                                 setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS);
122
123                 if (type == null || type == PolicyIndexType.all) {
124                         for (PolicyIndexType pT: PolicyIndexType.values()) {
125                                 if (pT != PolicyIndexType.all) {
126                                         searchBuilder.addType(pT.toString());
127                                 }
128                         }
129                 } else {
130                         searchBuilder.addType(type.toString());
131                 }
132
133                 Search search = searchBuilder.build();
134                 JestResult result;
135                 try {
136                         result = jestClient.execute(search);
137                 } catch (IOException ioe) {
138                         LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + 
139                                         search + ": " + ioe.getMessage(), ioe);
140                         throw new IllegalStateException(ioe);
141                 }
142
143                 if (result.isSucceeded()) {
144                         if (LOGGER.isInfoEnabled()){
145                                 LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + 
146                                                 result.getPathToResult() + ":" + System.lineSeparator() +
147                                                 result.getJsonString());
148                         }
149                 } else {        
150                         /* Unsuccessful search */
151                         if (LOGGER.isWarnEnabled()){
152                                 LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + 
153                                                 result.getResponseCode() + ": " + 
154                                                 search.getURI() + ":" +
155                                                 result.getPathToResult() + ":" +
156                                                 result.getJsonString() + ":" +
157                                                 result.getErrorMessage());
158                         }
159
160                         String errorMessage = result.getErrorMessage();
161                         if (errorMessage != null && !errorMessage.isEmpty()) {
162                                 String xMessage = errorMessage;
163                                 if (errorMessage.contains("TokenMgrError")) {
164                                         int indexError = errorMessage.lastIndexOf("TokenMgrError");
165                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);
166                                 } else if (errorMessage.contains("QueryParsingException")) {
167                                         int indexError = errorMessage.lastIndexOf("QueryParsingException");
168                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);
169                                 } else if (errorMessage.contains("JsonParseException")) {
170                                         int indexError = errorMessage.lastIndexOf("JsonParseException");
171                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
172                                 } else if (errorMessage.contains("Parse Failure")) {
173                                         int indexError = errorMessage.lastIndexOf("Parse Failure");
174                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
175                                 } else if (errorMessage.contains("SearchParseException")) {
176                                         int indexError = errorMessage.lastIndexOf("SearchParseException");
177                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
178                                 } else {
179                                         xMessage = result.getErrorMessage();
180                                 }
181                                 throw new IllegalStateException(xMessage);
182                         }
183                 }
184
185                 return result;
186         }
187
188
189         @Override
190         public JestResult search(PolicyIndexType type, String text, 
191                         Map<String, String> filter_s) 
192                                         throws IllegalStateException, IllegalArgumentException {
193                 if (LOGGER.isTraceEnabled()){
194                         LOGGER.trace("ENTER: " + text);
195                 }
196
197                 if (filter_s == null || filter_s.size() == 0) {
198                         return search(type, text);
199                 }
200
201                 String matches_s = "";
202                 matches_s = "{\n" +
203                                 "    \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" +
204                                 "    \"query\": {\n" +
205                                 "        \"bool\" : {\n" +
206                                 "            \"must\" : [";
207                 
208                 String match_params = "";
209                 for(Entry<String, String> entry : filter_s.entrySet()){
210                         String key = entry.getKey();
211                         String value = entry.getValue();
212                         if(filter_s.size() == 1){
213                                 match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }";
214                         }else{
215                                 match_params = match_params + "match\" : { \""+key+"\" : \""+value+"\" } ,";
216                         }
217                 }
218                 if(match_params.endsWith(",")){
219                         match_params = match_params.substring(0, match_params.length()-1);
220                 }
221
222                 matches_s = matches_s + "{\n" + match_params + "\n}" ;
223                 
224                 boolean query = false;
225                 String query_String = "";
226                 if(text != null){
227                         query = true;
228                         query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}";
229                 }
230                 
231                 if(query){
232                         matches_s = matches_s + "," +  query_String + "]\n}\n}\n}";
233                 }else{
234                         matches_s = matches_s + "]\n}\n}\n}";
235                 }
236                                 
237                 Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY);
238
239                 if (type == null || type == PolicyIndexType.all) {
240                         for (PolicyIndexType pT: PolicyIndexType.values()) {
241                                 if (pT != PolicyIndexType.all) {
242                                         searchBuilder.addType(pT.toString());
243                                 }
244                         }
245                 } else {
246                         searchBuilder.addType(type.toString());
247                 }
248
249                 Search search = searchBuilder.build();
250
251                 JestResult result;
252                 try {
253                         result = jestClient.execute(search);
254                 } catch (IOException ioe) {
255                         LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + 
256                                         search + ": " + ioe.getMessage(), ioe);
257                         throw new IllegalStateException(ioe);
258                 }
259
260                 if (result.isSucceeded()) {
261                         if (LOGGER.isInfoEnabled()){
262                                 LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + 
263                                                 result.getPathToResult() + ":" + System.lineSeparator() +
264                                                 result.getJsonString());        
265                         }       
266                 } else {        
267                         /* Unsuccessful search */
268                         if (LOGGER.isWarnEnabled()){
269                                 LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + 
270                                                 result.getResponseCode() + ": " + 
271                                                 search.getURI() + ":" +
272                                                 result.getPathToResult() + ":" +
273                                                 result.getJsonString() + ":" +
274                                                 result.getErrorMessage());
275                         }
276
277                         String errorMessage = result.getErrorMessage();
278                         if (errorMessage != null && !errorMessage.isEmpty()) {
279                                 String xMessage = errorMessage;
280                                 if (errorMessage.contains("TokenMgrError")) {
281                                         int indexError = errorMessage.lastIndexOf("TokenMgrError");
282                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);
283                                 } else if (errorMessage.contains("QueryParsingException")) {
284                                         int indexError = errorMessage.lastIndexOf("QueryParsingException");
285                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);
286                                 } else if (errorMessage.contains("JsonParseException")) {
287                                         int indexError = errorMessage.lastIndexOf("JsonParseException");
288                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
289                                 } else if (errorMessage.contains("Parse Failure")) {
290                                         int indexError = errorMessage.lastIndexOf("Parse Failure");
291                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
292                                 } else if (errorMessage.contains("SearchParseException")) {
293                                         int indexError = errorMessage.lastIndexOf("SearchParseException");
294                                         xMessage = "Invalid Search Expression.  Details: " + errorMessage.substring(indexError);                                
295                                 } else {
296                                         xMessage = result.getErrorMessage();
297                                 }
298                                 throw new IllegalStateException(xMessage);
299                         }
300                 }
301
302                 return result;
303         }
304
305         public boolean put(PolicyRestAdapter policyData) 
306                         throws IOException, IllegalStateException {
307                 if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER");
308
309                 PolicyIndexType indexType;
310                 try {
311                         String policyName = policyData.getNewFileName();
312                         if(policyName.contains("Config_")){
313                                 policyName = policyName.replace(".Config_", ":Config_");
314                         }else if(policyName.contains("Action_")){
315                                 policyName = policyName.replace(".Action_", ":Action_");
316                         }else if(policyName.contains("Decision_")){
317                                 policyName = policyName.replace(".Decision_", ":Decision_");
318                         }
319                         
320                         String[] splitPolicyName = policyName.split(":");
321                         indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
322                 } catch (IllegalArgumentException e) {
323                         throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage());                    
324                 }
325                 PolicyElasticData elasticData = new PolicyElasticData(policyData);
326                 JSONObject jsonObj = new JSONObject(elasticData);
327                 Index elkPut = new Index.Builder(jsonObj.toString()).
328                                 index(ELK_INDEX_POLICY).
329                                 type(indexType.name()).
330                                 id(elasticData.getPolicyName()).
331                                 refresh(true).
332                                 build();
333
334                 JestResult result = jestClient.execute(elkPut);
335
336                 if (result.isSucceeded()) {
337                         if (LOGGER.isInfoEnabled())
338                                 LOGGER.info("OK: PUT operation of " + "->"  + ": " +
339                                                 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
340                                                 result.getPathToResult() + "]" + System.lineSeparator() +
341                                                 result.getJsonString());
342                 } else {
343                         if (LOGGER.isWarnEnabled())
344                                 LOGGER.warn("FAILURE: PUT operation of "+ "->" + ": " +
345                                                 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
346                                                 result.getPathToResult() + "]" + System.lineSeparator() +
347                                                 result.getJsonString());                        
348
349                 }
350
351                 return result.isSucceeded();
352         }
353
354         @Override
355         public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException  {
356                 PolicyIndexType indexType = null;
357                 JestResult result;
358                 try {
359                         String policyName = policyData.getNewFileName();
360                         if(policyName.contains("Config_")){
361                                 policyName = policyName.replace(".Config_", ":Config_");
362                         }else if(policyName.contains("Action_")){
363                                 policyName = policyName.replace(".Action_", ":Action_");
364                         }else if(policyName.contains("Decision_")){
365                                 policyName = policyName.replace(".Decision_", ":Decision_");
366                         }
367                         
368                         String[] splitPolicyName = policyName.split(":");
369                         indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
370                         if (!isType(indexType)) {
371                                 throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY +
372                                                 " Type: " + indexType + 
373                                                 " is not configured");
374                         }
375                         PolicyElasticData elasticData = new PolicyElasticData(policyData);
376                         Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY).
377                                         type(indexType.name()).build();
378                         result = jestClient.execute(deleteRequest);
379                 } catch (IllegalArgumentException | IOException e) {
380                         LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + 
381                                         indexType +  ": null" + ":" + policyData.getNewFileName() + ": " + 
382                                         e.getMessage(), e);
383                         throw new IllegalStateException(e);
384                 }
385
386                 if (result.isSucceeded()) {
387                         if (LOGGER.isInfoEnabled())
388                                 LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
389                                                 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
390                                                 result.getPathToResult() + "]" + System.lineSeparator() +
391                                                 result.getJsonString());
392                 } else {
393                         if (LOGGER.isWarnEnabled())
394                                 LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
395                                                 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
396                                                 result.getPathToResult() + "]" + System.lineSeparator() +
397                                                 result.getJsonString());        
398                 }
399
400                 return result.isSucceeded();
401         }
402         
403         @Override
404         public boolean update(PolicyRestAdapter policyData) throws IllegalStateException  {     
405                 if (LOGGER.isDebugEnabled()){
406                         LOGGER.debug("ENTER");
407                 }
408                 try {
409                         boolean success = put(policyData);      
410                         return success;         
411                 } catch (Exception e) {
412                         LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e);
413                         throw new IllegalStateException(e);                     
414                 }
415         }
416 }