Merge "Added JUNITS for ONAP-REST Component"
[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.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("please check the elk configuration");
100                                         }
101                                 } catch (Exception e) {
102                                         LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
103                                 } 
104                         }
105                 }
106
107                 Builder bulk = null;
108                 
109                 HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build();
110                 jestFactory.setHttpClientConfig(httpClientConfig);
111             JestHttpClient client = (JestHttpClient) jestFactory.getObject();
112             
113                 Connection conn = null;
114                 Statement stmt = null;
115                 
116                 List<Index> listIndex = new ArrayList<Index>();
117                 
118                 try {
119                         Class.forName(databaseDriver);
120                         conn = DriverManager.getConnection(databseUrl, userName, password);
121                         stmt = conn.createStatement();
122                         
123                         String policyEntityQuery = "Select * from PolicyEntity";
124                         ResultSet result = stmt.executeQuery(policyEntityQuery);
125                         
126                         while(result.next()){
127                                 StringBuilder policyDataString = new StringBuilder("{");
128                                 String scope = result.getString("scope");
129                                 String policyName = result.getString("policyName");
130                                 if(policyName != null){
131                                         policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\",");
132                                 }
133                                 String description = result.getString("description");
134                                 if(description != null){
135                                         policyDataString.append("\"policyDescription\":\""+description+"\",");
136                                 }
137                                 Object policyData = result.getString("policydata");
138                                 
139                                 if(scope != null){
140                                         policyDataString.append("\"scope\":\""+scope+"\",");
141                                 }
142                                 String actionbodyid = result.getString("actionbodyid");
143                                 String configurationdataid = result.getString("configurationdataid");
144                                 
145                                 
146                                 String policyWithScopeName = scope + "." + policyName;
147                                 String _type = null;
148                                 
149                                 if(policyWithScopeName.contains(".Config_")){
150                                         policyDataString.append("\"policyType\":\"Config\",");
151                                         if(policyWithScopeName.contains(".Config_Fault_")){
152                                                 _type = "closedloop";
153                                                 policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\",");
154                                         }else if(policyWithScopeName.contains(".Config_PM_")){
155                                                 _type = "closedloop";
156                                                 policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\",");
157                                         }else{
158                                                 _type = "config";
159                                                 policyDataString.append("\"configPolicyType\":\"Base\",");
160                                         }
161                                 }else if(policyWithScopeName.contains(".Action_")){
162                                         _type = "action";
163                                         policyDataString.append("\"policyType\":\"Action\",");
164                                 }else if(policyWithScopeName.contains(".Decision_")){
165                                         _type = "decision";
166                                         policyDataString.append("\"policyType\":\"Decision\",");
167                                 }
168                                 
169                                 if(!"decision".equals(_type)){
170                                         if(configurationdataid != null){
171                                                 String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
172                                                 PreparedStatement pstmt = null;
173                                                 pstmt = conn.prepareStatement(configEntityQuery);
174                                             pstmt.setString(1, configurationdataid);
175                                                 ResultSet configResult = pstmt.executeQuery();
176                                                 while(configResult.next()){
177                                                         String configBody = configResult.getString("configbody");
178                                                         String configType = configResult.getString("configtype");
179                                                         if(configBody!=null){
180                                                                 configBody = configBody.replace("null", "\"\"");
181                                                                 configBody= configBody.replace("\"", "\\\"");
182                                                                 policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
183                                                         }
184                                                 }
185                                                 configResult.close();
186                                         }
187                                         
188                                         if(actionbodyid != null){
189                                                 String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
190                                                 PreparedStatement pstmt = null;
191                                                 pstmt = conn.prepareStatement(actionEntityQuery);
192                                             pstmt.setString(1, actionbodyid);
193                                                 ResultSet actionResult = pstmt.executeQuery();
194                                                 while(actionResult.next()){
195                                                         String actionBody = actionResult.getString("actionbody");
196                                                         actionBody = actionBody.replace("null", "\"\"");
197                                                         actionBody = actionBody.replace("\"", "\\\"");
198                                                         policyDataString.append("\"jsonBodyData\":\""+actionBody+"\",");
199                                                 }
200                                                 actionResult.close();
201                                         }       
202                                 }
203                                 
204                                 String _id = policyWithScopeName;
205                                 
206                                 String dataString = constructPolicyData(policyData, policyDataString);
207                                 dataString = dataString.substring(0, dataString.length()-1);
208                                 dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
209                                 dataString = dataString.replace("null", "\"\"");
210                                 dataString = dataString.replaceAll("\n", "");
211                                 
212                                 try{
213                                         Gson gson = new Gson();
214                                         gson.fromJson(dataString, Object.class);
215                                 }catch(Exception e){
216                                         LOGGER.error(e);
217                                         continue;
218                                 }
219                                 
220                                 if("config".equals(_type)){
221                                         listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
222                                 }else if("closedloop".equals(_type)){
223                                         listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
224                                 }else if("action".equals(_type)){
225                                         listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
226                                 }else if("decision".equals(_type)){
227                                         listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build());
228                                 }
229                         }
230                         
231                         result.close();
232                         bulk = new Bulk.Builder();
233                         for(int i =0; i < listIndex.size(); i++){
234                                 bulk.addAction(listIndex.get(i));
235                         }
236                         BulkResult searchResult = client.execute(bulk.build());
237                         if(searchResult.isSucceeded()){
238                                 LOGGER.debug("Success");
239                         }else{
240                                 LOGGER.error("Failure");
241                         }
242                 } catch (Exception e) {
243                         LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
244                 }finally{
245                         if(conn != null){
246                                 try {
247                                         conn.close();
248                                 } catch (Exception e) {
249                                         LOGGER.error("Exception Occured while closing the connection"+e);
250                                 }
251                         }
252                 }
253         }
254         
255         private static String constructPolicyData(Object policyData, StringBuilder policyDataString){
256                 if(policyData instanceof PolicyType){
257                         PolicyType policy = (PolicyType) policyData;
258                         TargetType target = policy.getTarget();
259                         if (target != null) {
260                                 // Under target we have AnyOFType
261                                 List<AnyOfType> anyOfList = target.getAnyOf();
262                                 if (anyOfList != null) {
263                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
264                                         while (iterAnyOf.hasNext()) {
265                                                 AnyOfType anyOf = iterAnyOf.next();
266                                                 // Under AnyOFType we have AllOFType
267                                                 List<AllOfType> allOfList = anyOf.getAllOf();
268                                                 if (allOfList != null) {
269                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
270                                                         while (iterAllOf.hasNext()) {
271                                                                 AllOfType allOf = iterAllOf.next();
272                                                                 // Under AllOFType we have Match
273                                                                 List<MatchType> matchList = allOf.getMatch();
274                                                                 if (matchList != null) {
275                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
276                                                                         while (iterMatch.hasNext()) {
277                                                                                 MatchType match = iterMatch.next();
278                                                                                 //
279                                                                                 // Under the match we have attribute value and
280                                                                                 // attributeDesignator. So,finally down to the actual attribute.
281                                                                                 //
282                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
283                                                                                 String value = (String) attributeValue.getContent().get(0);
284                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
285                                                                                 String attributeId = designator.getAttributeId();
286                                                                                 // First match in the target is OnapName, so set that value.
287                                                                                 if ("ONAPName".equals(attributeId)) {
288                                                                                         policyDataString.append("\"onapName\":\""+value+"\",");
289                                                                                 }
290                                                                                 if ("RiskType".equals(attributeId)){
291                                                                                         policyDataString.append("\"riskType\":\""+value+"\",");
292                                                                                 }
293                                                                                 if ("RiskLevel".equals(attributeId)){
294                                                                                         policyDataString.append("\"riskLevel\":\""+value+"\",");
295                                                                                 }
296                                                                                 if ("guard".equals(attributeId)){
297                                                                                         policyDataString.append("\"guard\":\""+value+"\",");
298                                                                                 }
299                                                                                 if ("ConfigName".equals(attributeId)){
300                                                                                         policyDataString.append("\"configName\":\""+value+"\",");
301                                                                                 }
302                                                                         }
303                                                                 }
304                                                         }
305                                                 }
306                                         }
307                                 }
308                         }
309                 }
310                 return policyDataString.toString();
311         }
312         
313 }