2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.policy.pap.xacml.rest.elk.client;
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;
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
40 import com.google.gson.Gson;
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;
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.
67 * properties should be configured in policyelk.properties
70 public class ElasticSearchPolicyUpdate {
72 private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class);
73 protected final static JestClientFactory jestFactory = new JestClientFactory();
75 public static void main(String[] args) {
78 String databseUrl = null;
79 String userName = null;
80 String password = null;
81 String databaseDriver = null;
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());
89 if(file.toString().endsWith(".properties")){
91 InputStream in = new FileInputStream(file.toFile());
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 + ":");
102 } catch (Exception e) {
103 LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
110 HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build();
111 jestFactory.setHttpClientConfig(httpClientConfig);
112 JestHttpClient client = (JestHttpClient) jestFactory.getObject();
114 Connection conn = null;
115 Statement stmt = null;
117 List<Index> listIndex = new ArrayList<Index>();
120 Class.forName(databaseDriver);
121 conn = DriverManager.getConnection(databseUrl, userName, password);
122 stmt = conn.createStatement();
124 String policyEntityQuery = "Select * from PolicyEntity";
125 ResultSet result = stmt.executeQuery(policyEntityQuery);
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+"\",");
134 String description = result.getString("description");
135 if(description != null){
136 policyDataString.append("\"policyDescription\":\""+description+"\",");
138 Object policyData = result.getString("policydata");
141 policyDataString.append("\"scope\":\""+scope+"\",");
143 String actionbodyid = result.getString("actionbodyid");
144 String configurationdataid = result.getString("configurationdataid");
147 String policyWithScopeName = scope + "." + policyName;
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\",");
160 policyDataString.append("\"configPolicyType\":\"Base\",");
162 }else if(policyWithScopeName.contains(".Action_")){
164 policyDataString.append("\"policyType\":\"Action\",");
165 }else if(policyWithScopeName.contains(".Decision_")){
167 policyDataString.append("\"policyType\":\"Decision\",");
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+"\",");
189 configResult.close();
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+",");
202 actionResult.close();
206 String _id = policyWithScopeName;
208 policyDataString.append(constructPolicyData(policyData, policyDataString));
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", "");
217 Gson gson = new Gson();
218 gson.fromJson(dataString, Object.class);
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());
236 bulk = new Bulk.Builder();
237 for(int i =0; i < listIndex.size(); i++){
238 bulk.addAction(listIndex.get(i));
240 BulkResult searchResult = client.execute(bulk.build());
241 if(searchResult.isSucceeded()){
242 LOGGER.debug("Success");
244 LOGGER.error("Failure");
246 } catch (Exception e) {
247 LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
252 } catch (Exception e) {
253 LOGGER.error("Exception Occured while closing the connection"+e);
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();
283 // Under the match we have attribute value and
284 // attributeDesignator. So,finally down to the actual attribute.
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+"\",");
294 if ("RiskType".equals(attributeId)){
295 policyDataString.append("\"riskType\":\""+value+"\",");
297 if ("RiskLevel".equals(attributeId)){
298 policyDataString.append("\"riskLevel\":\""+value+"\",");
300 if ("guard".equals(attributeId)){
301 policyDataString.append("\"guard\":\""+value+"\",");
303 if ("ConfigName".equals(attributeId)){
304 policyDataString.append("\"configName\":\""+value+"\",");
314 return policyDataString.toString();