Policy Elastic Search Validation Enhancements
[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(configBody!=null){
181                                                                 configBody = configBody.replace("null", "\"\"");
182                                                                 configBody= configBody.replace("\"", "\\\"");
183                                                                 policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
184                                                         }
185                                                 }
186                                                 configResult.close();
187                                         }
188                                         
189                                         if(actionbodyid != null){
190                                                 String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
191                                                 PreparedStatement pstmt = null;
192                                                 pstmt = conn.prepareStatement(actionEntityQuery);
193                                             pstmt.setString(1, actionbodyid);
194                                                 ResultSet actionResult = pstmt.executeQuery();
195                                                 while(actionResult.next()){
196                                                         String actionBody = actionResult.getString("actionbody");
197                                                         actionBody = actionBody.replace("null", "\"\"");
198                                                         actionBody = actionBody.replace("\"", "\\\"");
199                                                         policyDataString.append("\"jsonBodyData\":\""+actionBody+"\",");
200                                                 }
201                                                 actionResult.close();
202                                         }       
203                                 }
204                                 
205                                 String _id = policyWithScopeName;
206                                 
207                                 String dataString = constructPolicyData(policyData, policyDataString);
208                                 dataString = dataString.substring(0, dataString.length()-1);
209                                 dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
210                                 dataString = dataString.replace("null", "\"\"");
211                                 dataString = dataString.replaceAll("\n", "");
212                                 
213                                 try{
214                                         Gson gson = new Gson();
215                                         gson.fromJson(dataString, Object.class);
216                                 }catch(Exception e){
217                                         LOGGER.error(e);
218                                         continue;
219                                 }
220                                 
221                                 if("config".equals(_type)){
222                                         listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
223                                 }else if("closedloop".equals(_type)){
224                                         listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
225                                 }else if("action".equals(_type)){
226                                         listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
227                                 }else if("decision".equals(_type)){
228                                         listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build());
229                                 }
230                         }
231                         
232                         result.close();
233                         bulk = new Bulk.Builder();
234                         for(int i =0; i < listIndex.size(); i++){
235                                 bulk.addAction(listIndex.get(i));
236                         }
237                         BulkResult searchResult = client.execute(bulk.build());
238                         if(searchResult.isSucceeded()){
239                                 LOGGER.debug("Success");
240                         }else{
241                                 LOGGER.error("Failure");
242                         }
243                 } catch (Exception e) {
244                         LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
245                 }finally{
246                         if(conn != null){
247                                 try {
248                                         conn.close();
249                                 } catch (Exception e) {
250                                         LOGGER.error("Exception Occured while closing the connection"+e);
251                                 }
252                         }
253                 }
254         }
255         
256         private static String constructPolicyData(Object policyData, StringBuilder policyDataString){
257                 if(policyData instanceof PolicyType){
258                         PolicyType policy = (PolicyType) policyData;
259                         TargetType target = policy.getTarget();
260                         if (target != null) {
261                                 // Under target we have AnyOFType
262                                 List<AnyOfType> anyOfList = target.getAnyOf();
263                                 if (anyOfList != null) {
264                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
265                                         while (iterAnyOf.hasNext()) {
266                                                 AnyOfType anyOf = iterAnyOf.next();
267                                                 // Under AnyOFType we have AllOFType
268                                                 List<AllOfType> allOfList = anyOf.getAllOf();
269                                                 if (allOfList != null) {
270                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
271                                                         while (iterAllOf.hasNext()) {
272                                                                 AllOfType allOf = iterAllOf.next();
273                                                                 // Under AllOFType we have Match
274                                                                 List<MatchType> matchList = allOf.getMatch();
275                                                                 if (matchList != null) {
276                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
277                                                                         while (iterMatch.hasNext()) {
278                                                                                 MatchType match = iterMatch.next();
279                                                                                 //
280                                                                                 // Under the match we have attribute value and
281                                                                                 // attributeDesignator. So,finally down to the actual attribute.
282                                                                                 //
283                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
284                                                                                 String value = (String) attributeValue.getContent().get(0);
285                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
286                                                                                 String attributeId = designator.getAttributeId();
287                                                                                 // First match in the target is OnapName, so set that value.
288                                                                                 if ("ONAPName".equals(attributeId)) {
289                                                                                         policyDataString.append("\"onapName\":\""+value+"\",");
290                                                                                 }
291                                                                                 if ("RiskType".equals(attributeId)){
292                                                                                         policyDataString.append("\"riskType\":\""+value+"\",");
293                                                                                 }
294                                                                                 if ("RiskLevel".equals(attributeId)){
295                                                                                         policyDataString.append("\"riskLevel\":\""+value+"\",");
296                                                                                 }
297                                                                                 if ("guard".equals(attributeId)){
298                                                                                         policyDataString.append("\"guard\":\""+value+"\",");
299                                                                                 }
300                                                                                 if ("ConfigName".equals(attributeId)){
301                                                                                         policyDataString.append("\"configName\":\""+value+"\",");
302                                                                                 }
303                                                                         }
304                                                                 }
305                                                         }
306                                                 }
307                                         }
308                                 }
309                         }
310                 }
311                 return policyDataString.toString();
312         }
313         
314 }