Sonar fix forONAP-PAP-REST critical sonar issues
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / elk / client / ElasticSearchPolicyUpdate.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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.onap.policy.pap.xacml.rest.elk.client;
21
22 import java.io.FileInputStream;
23 import java.io.InputStream;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.sql.Connection;
28 import java.sql.DriverManager;
29 import java.sql.PreparedStatement;
30 import java.sql.ResultSet;
31 import java.sql.Statement;
32 import java.util.ArrayList;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Properties;
36
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
39
40 import com.google.gson.Gson;
41
42 import io.searchbox.client.JestClientFactory;
43 import io.searchbox.client.config.HttpClientConfig;
44 import io.searchbox.client.http.JestHttpClient;
45 import io.searchbox.core.Bulk;
46 import io.searchbox.core.Bulk.Builder;
47 import io.searchbox.core.BulkResult;
48 import io.searchbox.core.Index;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
56
57
58
59 /**
60  * This code will deals with parsing the XACML content on reading from 
61  * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables)
62  * and convert the data into json to do bulk operation on putting to elastic search database.
63  * Which is used to support Elastic Search in Policy Application GUI to search policies.
64  * 
65  * 
66  * 
67  * properties should be configured in policyelk.properties
68  *
69  */
70 public class ElasticSearchPolicyUpdate {
71         
72         private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class);
73         protected final static JestClientFactory jestFactory = new JestClientFactory();
74         
75         public static void main(String[] args) {
76                 
77                 String elkURL = null;
78                 String databseUrl = null;
79                 String userName = null;
80                 String password = null;
81                 String databaseDriver = null; 
82                 
83                 String propertyFile = System.getProperty("PROPERTY_FILE");
84                 Properties config = new Properties();
85                 Path file = Paths.get(propertyFile);
86                 if(Files.notExists(file)){
87                         LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
88                 }else{
89                         if(file.toString().endsWith(".properties")){
90                                 try {
91                                         InputStream in = new FileInputStream(file.toFile());
92                                         config.load(in);
93                                         elkURL = config.getProperty("policy.elk.url");
94                                         databseUrl = config.getProperty("policy.database.url");
95                                         userName = config.getProperty("policy.database.username");
96                                         password = config.getProperty("policy.database.password");
97                                         databaseDriver = config.getProperty("policy.database.driver");
98                                         if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){
99                                                 LOGGER.error("One of the Property is null in policyelk.properties = elkurl:databaseurl:username:password:databasedriver  " 
100                                                                 + elkURL + ":"+ databseUrl + ":"+ userName + ":"+ password + ":"+ databaseDriver + ":");
101                                         }
102                                 } catch (Exception e) {
103                                         LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
104                                 } 
105                         }
106                 }
107
108                 Builder bulk = null;
109                 
110                 HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build();
111                 jestFactory.setHttpClientConfig(httpClientConfig);
112             JestHttpClient client = (JestHttpClient) jestFactory.getObject();
113             
114                 Connection conn = null;
115                 Statement stmt = null;
116                 
117                 List<Index> listIndex = new ArrayList<Index>();
118                 
119                 try {
120                         Class.forName(databaseDriver);
121                         conn = DriverManager.getConnection(databseUrl, userName, password);
122                         stmt = conn.createStatement();
123                         
124                         String policyEntityQuery = "Select * from PolicyEntity";
125                         ResultSet result = stmt.executeQuery(policyEntityQuery);
126                         
127                         while(result.next()){
128                                 StringBuilder policyDataString = new StringBuilder("{");
129                                 String scope = result.getString("scope");
130                                 String policyName = result.getString("policyName");
131                                 if(policyName != null){
132                                         policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\",");
133                                 }
134                                 String description = result.getString("description");
135                                 if(description != null){
136                                         policyDataString.append("\"policyDescription\":\""+description+"\",");
137                                 }
138                                 Object policyData = result.getString("policydata");
139                                 
140                                 if(scope != null){
141                                         policyDataString.append("\"scope\":\""+scope+"\",");
142                                 }
143                                 String actionbodyid = result.getString("actionbodyid");
144                                 String configurationdataid = result.getString("configurationdataid");
145                                 
146                                 
147                                 String policyWithScopeName = scope + "." + policyName;
148                                 String _type = null;
149                                 
150                                 if(policyWithScopeName.contains(".Config_")){
151                                         policyDataString.append("\"policyType\":\"Config\",");
152                                         if(policyWithScopeName.contains(".Config_Fault_")){
153                                                 _type = "closedloop";
154                                                 policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\",");
155                                         }else if(policyWithScopeName.contains(".Config_PM_")){
156                                                 _type = "closedloop";
157                                                 policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\",");
158                                         }else{
159                                                 _type = "config";
160                                                 policyDataString.append("\"configPolicyType\":\"Base\",");
161                                         }
162                                 }else if(policyWithScopeName.contains(".Action_")){
163                                         _type = "action";
164                                         policyDataString.append("\"policyType\":\"Action\",");
165                                 }else if(policyWithScopeName.contains(".Decision_")){
166                                         _type = "decision";
167                                         policyDataString.append("\"policyType\":\"Decision\",");
168                                 }
169                                 
170                                 if(!"decision".equals(_type)){
171                                         if(configurationdataid != null){
172                                                 String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
173                                                 PreparedStatement pstmt = null;
174                                                 pstmt = conn.prepareStatement(configEntityQuery);
175                                             pstmt.setString(1, configurationdataid);
176                                                 ResultSet configResult = pstmt.executeQuery();
177                                                 while(configResult.next()){
178                                                         String configBody = configResult.getString("configbody");
179                                                         String configType = configResult.getString("configtype");
180                                                         if("JSON".equalsIgnoreCase(configType)){
181                                                                 policyDataString.append("\"jsonBodyData\":"+configBody+",\"configType\":\""+configType+"\",");
182                                                         }else if("OTHER".equalsIgnoreCase(configType)){
183                                                                 if(configBody!=null){
184                                                                         configBody= configBody.replaceAll("\"", "");
185                                                                         policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
186                                                                 }
187                                                         }
188                                                 }
189                                                 configResult.close();
190                                         }
191                                         
192                                         if(actionbodyid != null){
193                                                 String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
194                                                 PreparedStatement pstmt = null;
195                                                 pstmt = conn.prepareStatement(actionEntityQuery);
196                                             pstmt.setString(1, actionbodyid);
197                                                 ResultSet actionResult = pstmt.executeQuery();
198                                                 while(actionResult.next()){
199                                                         String actionBody = actionResult.getString("actionbody");
200                                                         policyDataString.append("\"jsonBodyData\":"+actionBody+",");
201                                                 }
202                                                 actionResult.close();
203                                         }       
204                                 }
205                                 
206                                 String _id = policyWithScopeName;
207                                 
208                                 policyDataString.append(constructPolicyData(policyData, policyDataString));
209                                 
210                                 String dataString = policyDataString.toString();
211                                 dataString = dataString.substring(0, dataString.length()-1);
212                                 dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
213                                 dataString = dataString.replace("null", "\"\"");
214                                 dataString = dataString.replaceAll(" ", "").replaceAll("\n", "");
215                                 
216                                 try{
217                                         Gson gson = new Gson();
218                                         gson.fromJson(dataString, Object.class);
219                                 }catch(Exception e){
220                                         LOGGER.error(e);
221                                         continue;
222                                 }
223                                 
224                                 if("config".equals(_type)){
225                                         listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
226                                 }else if("closedloop".equals(_type)){
227                                         listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
228                                 }else if("action".equals(_type)){
229                                         listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
230                                 }else if("decision".equals(_type)){
231                                         listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build());
232                                 }
233                         }
234                         
235                         result.close();
236                         bulk = new Bulk.Builder();
237                         for(int i =0; i < listIndex.size(); i++){
238                                 bulk.addAction(listIndex.get(i));
239                         }
240                         BulkResult searchResult = client.execute(bulk.build());
241                         if(searchResult.isSucceeded()){
242                                 LOGGER.debug("Success");
243                         }else{
244                                 LOGGER.error("Failure");
245                         }
246                 } catch (Exception e) {
247                         LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
248                 }finally{
249                         if(conn != null){
250                                 try {
251                                         conn.close();
252                                 } catch (Exception e) {
253                                         LOGGER.error("Exception Occured while closing the connection"+e);
254                                 }
255                         }
256                 }
257         }
258         
259         private static String constructPolicyData(Object policyData, StringBuilder policyDataString){
260                 if(policyData instanceof PolicyType){
261                         PolicyType policy = (PolicyType) policyData;
262                         TargetType target = policy.getTarget();
263                         if (target != null) {
264                                 // Under target we have AnyOFType
265                                 List<AnyOfType> anyOfList = target.getAnyOf();
266                                 if (anyOfList != null) {
267                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
268                                         while (iterAnyOf.hasNext()) {
269                                                 AnyOfType anyOf = iterAnyOf.next();
270                                                 // Under AnyOFType we have AllOFType
271                                                 List<AllOfType> allOfList = anyOf.getAllOf();
272                                                 if (allOfList != null) {
273                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
274                                                         while (iterAllOf.hasNext()) {
275                                                                 AllOfType allOf = iterAllOf.next();
276                                                                 // Under AllOFType we have Match
277                                                                 List<MatchType> matchList = allOf.getMatch();
278                                                                 if (matchList != null) {
279                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
280                                                                         while (iterMatch.hasNext()) {
281                                                                                 MatchType match = iterMatch.next();
282                                                                                 //
283                                                                                 // Under the match we have attribute value and
284                                                                                 // attributeDesignator. So,finally down to the actual attribute.
285                                                                                 //
286                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
287                                                                                 String value = (String) attributeValue.getContent().get(0);
288                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
289                                                                                 String attributeId = designator.getAttributeId();
290                                                                                 // First match in the target is OnapName, so set that value.
291                                                                                 if ("ONAPName".equals(attributeId)) {
292                                                                                         policyDataString.append("\"onapName\":\""+value+"\",");
293                                                                                 }
294                                                                                 if ("RiskType".equals(attributeId)){
295                                                                                         policyDataString.append("\"riskType\":\""+value+"\",");
296                                                                                 }
297                                                                                 if ("RiskLevel".equals(attributeId)){
298                                                                                         policyDataString.append("\"riskLevel\":\""+value+"\",");
299                                                                                 }
300                                                                                 if ("guard".equals(attributeId)){
301                                                                                         policyDataString.append("\"guard\":\""+value+"\",");
302                                                                                 }
303                                                                                 if ("ConfigName".equals(attributeId)){
304                                                                                         policyDataString.append("\"configName\":\""+value+"\",");
305                                                                                 }
306                                                                         }
307                                                                 }
308                                                         }
309                                                 }
310                                         }
311                                 }
312                         }
313                 }
314                 return policyDataString.toString();
315         }
316         
317 }