Fix all bugs reported by Sonar in policy/engine
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / elk / client / ElasticSearchPolicyUpdate.java
index ee6fd05..dcabefc 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 package org.onap.policy.pap.xacml.rest.elk.client;
 
+import java.io.ByteArrayInputStream;
 import java.io.FileInputStream;
 import java.io.InputStream;
-import java.nio.file.Files;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.sql.Connection;
@@ -36,6 +37,8 @@ import java.util.Properties;
 
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.xacml.util.XACMLPolicyScanner;
 
 import com.google.gson.Gson;
 
@@ -77,13 +80,13 @@ public class ElasticSearchPolicyUpdate {
                String elkURL = null;
                String databseUrl = null;
                String userName = null;
-               String password = null;
+               String txt = null;
                String databaseDriver = null; 
                
                String propertyFile = System.getProperty("PROPERTY_FILE");
                Properties config = new Properties();
                Path file = Paths.get(propertyFile);
-               if(Files.notExists(file)){
+               if(!file.toFile().exists()){
                        LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
                }else{
                        if(file.toString().endsWith(".properties")){
@@ -93,11 +96,10 @@ public class ElasticSearchPolicyUpdate {
                                        elkURL = config.getProperty("policy.elk.url");
                                        databseUrl = config.getProperty("policy.database.url");
                                        userName = config.getProperty("policy.database.username");
-                                       password = config.getProperty("policy.database.password");
+                                       txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password"));
                                        databaseDriver = config.getProperty("policy.database.driver");
-                                       if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){
-                                               LOGGER.error("One of the Property is null in policyelk.properties = elkurl:databaseurl:username:password:databasedriver  " 
-                                                               + elkURL + ":"+ databseUrl + ":"+ userName + ":"+ password + ":"+ databaseDriver + ":");
+                                       if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){
+                                               LOGGER.error("please check the elk configuration");
                                        }
                                } catch (Exception e) {
                                        LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
@@ -113,16 +115,17 @@ public class ElasticSearchPolicyUpdate {
            
                Connection conn = null;
                Statement stmt = null;
+               ResultSet result = null;
                
-               List<Index> listIndex = new ArrayList<Index>();
+               List<Index> listIndex = new ArrayList<>();
                
                try {
                        Class.forName(databaseDriver);
-                       conn = DriverManager.getConnection(databseUrl, userName, password);
+                       conn = DriverManager.getConnection(databseUrl, userName, txt);
                        stmt = conn.createStatement();
                        
                        String policyEntityQuery = "Select * from PolicyEntity";
-                       ResultSet result = stmt.executeQuery(policyEntityQuery);
+                       result = stmt.executeQuery(policyEntityQuery);
                        
                        while(result.next()){
                                StringBuilder policyDataString = new StringBuilder("{");
@@ -169,49 +172,20 @@ public class ElasticSearchPolicyUpdate {
                                
                                if(!"decision".equals(_type)){
                                        if(configurationdataid != null){
-                                               String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
-                                               PreparedStatement pstmt = null;
-                                               pstmt = conn.prepareStatement(configEntityQuery);
-                                           pstmt.setString(1, configurationdataid);
-                                               ResultSet configResult = pstmt.executeQuery();
-                                               while(configResult.next()){
-                                                       String configBody = configResult.getString("configbody");
-                                                       String configType = configResult.getString("configtype");
-                                                       if("JSON".equalsIgnoreCase(configType)){
-                                                               policyDataString.append("\"jsonBodyData\":"+configBody+",\"configType\":\""+configType+"\",");
-                                                       }else if("OTHER".equalsIgnoreCase(configType)){
-                                                               if(configBody!=null){
-                                                                       configBody= configBody.replaceAll("\"", "");
-                                                                       policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
-                                                               }
-                                                       }
-                                               }
-                                               configResult.close();
+                                           updateConfigData(conn, configurationdataid, policyDataString);
                                        }
-                                       
                                        if(actionbodyid != null){
-                                               String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
-                                               PreparedStatement pstmt = null;
-                                               pstmt = conn.prepareStatement(actionEntityQuery);
-                                           pstmt.setString(1, actionbodyid);
-                                               ResultSet actionResult = pstmt.executeQuery();
-                                               while(actionResult.next()){
-                                                       String actionBody = actionResult.getString("actionbody");
-                                                       policyDataString.append("\"jsonBodyData\":"+actionBody+",");
-                                               }
-                                               actionResult.close();
+                                           updateActionData(conn, actionbodyid, policyDataString);
                                        }       
                                }
                                
                                String _id = policyWithScopeName;
                                
-                               policyDataString.append(constructPolicyData(policyData, policyDataString));
-                               
-                               String dataString = policyDataString.toString();
+                               String dataString = constructPolicyData(policyData, policyDataString);
                                dataString = dataString.substring(0, dataString.length()-1);
                                dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
                                dataString = dataString.replace("null", "\"\"");
-                               dataString = dataString.replaceAll(" ", "").replaceAll("\n", "");
+                               dataString = dataString.replaceAll("\n", "");
                                
                                try{
                                        Gson gson = new Gson();
@@ -246,6 +220,20 @@ public class ElasticSearchPolicyUpdate {
                } catch (Exception e) {
                        LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
                }finally{
+                       if(result != null){
+                           try {
+                               result.close();
+                           } catch (Exception e) {
+                               LOGGER.error("Exception Occured while closing the resultset"+e);
+                           }
+                       }
+                       if(stmt != null){
+                           try {
+                               stmt.close();
+                           } catch (Exception e) {
+                               LOGGER.error("Exception Occured while closing the statement"+e);
+                           }
+                       }
                        if(conn != null){
                                try {
                                        conn.close();
@@ -256,7 +244,9 @@ public class ElasticSearchPolicyUpdate {
                }
        }
        
-       private static String constructPolicyData(Object policyData, StringBuilder policyDataString){
+       public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){
+               InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8));
+               Object policyData = XACMLPolicyScanner.readPolicy(stream);
                if(policyData instanceof PolicyType){
                        PolicyType policy = (PolicyType) policyData;
                        TargetType target = policy.getTarget();
@@ -314,4 +304,79 @@ public class ElasticSearchPolicyUpdate {
                return policyDataString.toString();
        }
        
+       private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception {
+
+               PreparedStatement pstmt = null;
+               ResultSet configResult = null;
+               try {
+                   String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
+                   pstmt = null;
+                   pstmt = conn.prepareStatement(configEntityQuery);
+                   pstmt.setString(1, configurationdataid);
+                   configResult = pstmt.executeQuery();
+                   while(configResult.next()){
+                       String configBody = configResult.getString("configbody");
+                       String configType = configResult.getString("configtype");
+                       if(configBody!=null){
+                           configBody = configBody.replace("null", "\"\"");
+                           configBody= configBody.replace("\"", "\\\"");
+                           policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
+                       }
+                   }
+               } catch(Exception e) {
+                   LOGGER.error("Exception Occured while updating configData"+e);
+                   throw(e);
+               } finally {
+                   if(configResult != null){
+                       try {
+                           configResult.close();
+                       } catch (Exception e) {
+                           LOGGER.error("Exception Occured while closing the ResultSet"+e);
+                       }
+                   }
+                   if(pstmt != null){
+                       try {
+                           pstmt.close();
+                       } catch (Exception e) {
+                           LOGGER.error("Exception Occured while closing the PreparedStatement"+e);
+                       }
+                   }
+              }
+       }
+       
+       private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception {
+
+            PreparedStatement pstmt = null;
+            ResultSet actionResult = null;
+            try {
+                String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
+                pstmt = conn.prepareStatement(actionEntityQuery);
+                pstmt.setString(1, actionbodyid);
+                actionResult = pstmt.executeQuery();
+                while(actionResult.next()){
+                    String actionBody = actionResult.getString("actionbody");
+                    actionBody = actionBody.replace("null", "\"\"");
+                    actionBody = actionBody.replace("\"", "\\\"");
+                    policyDataString.append("\"jsonBodyData\":\""+actionBody+"\",");
+                }
+            } catch(Exception e) {
+                LOGGER.error("Exception Occured while updating actionData"+e);
+                throw(e);
+            } finally {
+                if(actionResult != null){
+                    try {
+                        actionResult.close();
+                    } catch (Exception e) {
+                        LOGGER.error("Exception Occured while closing the ResultSet"+e);
+                    }
+                }
+                if(pstmt != null){
+                    try {
+                        pstmt.close();
+                    } catch (Exception e) {
+                        LOGGER.error("Exception Occured while closing the PreparedStatement"+e);
+                    }
+                }
+           }
+       }
 }
\ No newline at end of file