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