More sonar cleanup and line consolidation
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyExportAndImportController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 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
21 package org.onap.policy.controller;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26
27 import java.io.BufferedWriter;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileOutputStream;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.util.ArrayList;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
38 import java.util.Set;
39
40 import javax.script.SimpleBindings;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43
44 import org.apache.poi.hssf.usermodel.HSSFRow;
45 import org.apache.poi.hssf.usermodel.HSSFSheet;
46 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
47 import org.apache.poi.ss.usermodel.Cell;
48 import org.apache.poi.ss.usermodel.Row;
49 import org.apache.poi.ss.usermodel.Sheet;
50 import org.json.JSONObject;
51 import org.onap.policy.admin.PolicyRestController;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.rest.adapter.PolicyExportAdapter;
55 import org.onap.policy.rest.dao.CommonClassDao;
56 import org.onap.policy.rest.jpa.ActionBodyEntity;
57 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
58 import org.onap.policy.rest.jpa.DCAEuuid;
59 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
60 import org.onap.policy.rest.jpa.MicroServiceConfigName;
61 import org.onap.policy.rest.jpa.MicroServiceLocation;
62 import org.onap.policy.rest.jpa.MicroServiceModels;
63 import org.onap.policy.rest.jpa.PolicyEditorScopes;
64 import org.onap.policy.rest.jpa.PolicyEntity;
65 import org.onap.policy.rest.jpa.PolicyVersion;
66 import org.onap.policy.rest.jpa.UserInfo;
67 import org.onap.policy.utils.UserUtils.Pair;
68 import org.onap.policy.xacml.api.XACMLErrorConstants;
69 import org.onap.portalsdk.core.controller.RestrictedBaseController;
70 import org.onap.portalsdk.core.web.support.UserUtils;
71 import org.springframework.stereotype.Controller;
72 import org.springframework.web.bind.annotation.RequestMapping;
73
74 @Controller
75 @RequestMapping("/")
76 public class PolicyExportAndImportController extends RestrictedBaseController {
77
78     private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
79
80     private static String superAdmin = "super-admin";
81     private static String superEditor = "super-editor";
82     private static String admin = "admin";
83     private static String editor = "editor";
84     private static String policyName = "policyName";
85     private static String configurationName = "configurationName";
86     private static String configurationbody = "configurationbody";
87     private static String config = "Config_";
88     private static final String CONFIG_MS = "Config_MS_";
89     private static final String NOTVALID = " is not valid.";
90     private static final String POLICY = "Policy:";
91     private static final String BODYSIZE = "bodySize";
92     private static final String DECISION_MS = "Decision_MS_";
93     private static final String ACTION = "Action_";
94     private static CommonClassDao commonClassDao;
95
96     private PolicyController policyController;
97
98     public PolicyController getPolicyController() {
99         return policyController;
100     }
101
102     public void setPolicyController(PolicyController policyController) {
103         this.policyController = policyController;
104     }
105
106     public static CommonClassDao getCommonClassDao() {
107         return commonClassDao;
108     }
109
110     public static void setCommonClassDao(CommonClassDao commonClassDao) {
111         PolicyExportAndImportController.commonClassDao = commonClassDao;
112     }
113
114     public PolicyExportAndImportController() {
115         // Empty constructor
116     }
117
118     /**
119      * This is for downloading existing policy.
120      *
121      * @param request HttpServletRequest
122      * @param response HttpServletResponse
123      * @throws IOException error out
124      */
125     @RequestMapping(
126             value = {"/policy_download/exportPolicy.htm"},
127             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
128     public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
129         try (HSSFWorkbook workBook2 = new HSSFWorkbook()) {
130             ArrayList<String> selectedPolicy = new ArrayList<>();
131             ObjectMapper mapper = new ObjectMapper();
132             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
133             JsonNode root = mapper.readTree(request.getReader());
134             PolicyExportAdapter adapter =
135                     mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
136             for (Object policyId : adapter.getPolicyDatas()) {
137                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
138                 String policyWithScope =
139                         selected.get(policyName).toString() + "." + selected.get("activeVersion").toString() + ".xml";
140                 String scope = policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator))
141                         .replace(File.separator, ".");
142                 String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1);
143                 selectedPolicy.add(policyNamel + ":" + scope);
144             }
145
146             HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
147             HSSFRow headingRow = sheet.createRow(0);
148             headingRow.createCell(0).setCellValue(policyName);
149             headingRow.createCell(1).setCellValue("scope");
150             headingRow.createCell(2).setCellValue("version");
151             headingRow.createCell(3).setCellValue("policyData");
152             headingRow.createCell(4).setCellValue("description");
153             headingRow.createCell(5).setCellValue(configurationName);
154             headingRow.createCell(6).setCellValue(BODYSIZE);
155             headingRow.createCell(7).setCellValue(configurationbody);
156
157             List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class,
158                     "policyName:scope", selectedPolicy);
159             processEntityData(entityData, sheet, headingRow); //
160             String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
161             String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
162             File deleteCheck = new File(deleteCheckPath);
163             if (deleteCheck.exists() && deleteCheck.delete()) {
164                 logger.info("Deleted the file from system before exporting a new file.");
165             }
166             File temPath = new File(tmp);
167             if (!temPath.exists()) {
168                 temPath.mkdir();
169             }
170
171             String file = temPath + File.separator + "PolicyExport.xls";
172             File filepath = new File(file);
173             FileOutputStream fos = new FileOutputStream(filepath);
174             workBook2.write(fos);
175             fos.flush();
176
177             response.setContentType("application / json");
178             request.setCharacterEncoding("UTF-8");
179
180             PrintWriter out = response.getWriter();
181             String successMap = file.substring(file.lastIndexOf("webapps") + 8);
182             String responseString = mapper.writeValueAsString(successMap);
183             JSONObject json = new JSONObject("{data: " + responseString + "}");
184             out.write(json.toString());
185         } catch (Exception e) {
186             logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e);
187         }
188     }
189
190     private void processEntityData(List<Object> entityData, HSSFSheet sheet, HSSFRow headingRow) {
191
192         short rowNo = 1;
193         for (Object object : entityData) {
194             PolicyEntity policyEntity = (PolicyEntity) object;
195             HSSFRow row = sheet.createRow(rowNo);
196             row.createCell(0).setCellValue(policyEntity.getPolicyName());
197             row.createCell(1).setCellValue(policyEntity.getScope());
198             row.createCell(2).setCellValue(policyEntity.getVersion());
199             row.createCell(3).setCellValue(policyEntity.getPolicyData());
200             row.createCell(4).setCellValue(policyEntity.getDescription());
201             if (policyEntity.getPolicyName().contains(DECISION_MS)
202                     || !policyEntity.getPolicyName().contains("Decision_")) {
203                 if (policyEntity.getConfigurationData() != null) {
204                     row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
205                     String body = policyEntity.getConfigurationData().getConfigBody();
206                     row = populateConfigParam(policyEntity, row, headingRow, body);
207                 }
208                 populateActionBodyEntity(policyEntity, row);
209             } else {
210                 row.createCell(5).setCellValue("");
211                 row.createCell(6).setCellValue(0);
212                 row.createCell(7).setCellValue("");
213             }
214             rowNo++;
215         }
216     }
217
218     private HSSFRow populateActionBodyEntity(PolicyEntity policyEntity, HSSFRow row) {
219         if (policyEntity.getActionBodyEntity() != null) {
220             row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
221             row.createCell(6).setCellValue(0);
222             row.createCell(7).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
223         }
224         return row;
225     }
226
227     private HSSFRow populateConfigParam(PolicyEntity policyEntity, HSSFRow row, HSSFRow headingRow, String body) {
228
229         if (policyEntity.getPolicyName().contains("Config_BRMS_Param_")) {
230             int index = 0;
231             int arraySize = 0;
232             while (index < body.length()) {
233                 if (arraySize == 0) {
234                     row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
235                 } else {
236                     headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize);
237                     row.createCell(7 + arraySize)
238                             .setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
239                 }
240                 index += 30000;
241                 arraySize += 1;
242             }
243             row.createCell(6).setCellValue(arraySize);
244         } else {
245             row.createCell(6).setCellValue(0);
246             row.createCell(7).setCellValue(body);
247         }
248         return row;
249     }
250
251     /**
252      * This is to upload a policy and save it to database.
253      *
254      * @param file String
255      * @param request HttpServletRequest
256      * @return JSONObject
257      * @throws IOException error out
258      */
259     public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException {
260         boolean configExists = false;
261         boolean actionExists = false;
262         String configName = null;
263         boolean finalColumn;
264         PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
265         String userId = UserUtils.getUserSession(request).getOrgUserId();
266         UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
267
268         // Check if the Role and Scope Size are Null get the values from db.
269         List<Object> userRoles = controller.getRoles(userId);
270         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
271         List<String> roles = pair.u;
272         Set<String> scopes = pair.t;
273
274         try (FileInputStream excelFile = new FileInputStream(new File(file));
275                 HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) {
276             Sheet datatypeSheet = workbook.getSheetAt(0);
277             Iterator<Row> rowIterator = datatypeSheet.iterator();
278
279             while (rowIterator.hasNext()) {
280                 finalColumn = false;
281                 PolicyEntity policyEntity = new PolicyEntity();
282                 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
283                 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
284                 Row currentRow = rowIterator.next();
285                 if (currentRow.getRowNum() == 0) {
286                     continue;
287                 }
288                 Iterator<Cell> cellIterator = currentRow.cellIterator();
289                 StringBuilder body = new StringBuilder();
290                 int bodySize = 0;
291                 int setBodySize = 0;
292                 boolean configurationBodySet = false;
293                 while (cellIterator.hasNext()) {
294                     Cell cell = cellIterator.next();
295                     if (policyName.equalsIgnoreCase(getCellHeaderName(cell))) {
296                         policyEntity.setPolicyName(cell.getStringCellValue());
297                         finalColumn = false;
298                         configurationBodySet = false;
299                         configExists = false;
300                         actionExists = false;
301                     }
302                     policyEntity = populatePolicyEntity(cell, policyEntity);
303                     setBodySize = getSetBodySize(policyEntity, cell, setBodySize);
304                     finalColumn = isFinalColumn(policyEntity, cell, setBodySize, setBodySize, finalColumn);
305                     configurationBodySet =
306                             isConfigurationBodySet(policyEntity, cell, setBodySize, setBodySize, configurationBodySet);
307                     configExists = isConfigExists(policyEntity, cell, configExists);
308                     body = addCellValue(policyEntity, cell, body);
309                     actionExists = isActionExists(policyEntity, cell, actionExists);
310                     actionBodyEntity = setActionBodyObject(policyEntity, actionBodyEntity, cell);
311                     bodySize = getBobySize(bodySize, cell); //
312                     configName = getConfigName(cell, configName);
313                     configurationDataEntity =
314                             populateConfigurationDataEntity(policyEntity, configurationDataEntity, cell);
315                     actionBodyEntity = populateActionBodyObject(policyEntity, actionBodyEntity, cell);
316                     JSONObject response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
317                     if (response != null) {
318                         return response;
319                     }
320                     savePolicyEntiies(finalColumn, configurationBodySet, configurationDataEntity, policyEntity,
321                             controller, roles, userInfo, scopes, configName, userId, configExists, actionExists,
322                             actionBodyEntity, body);
323
324                 }
325             }
326         } catch (IOException e) {
327             logger.error("Exception Occured While importing the Policy" + e);
328         }
329         return null;
330     }
331
332     private void writeConfigurationFile(ConfigurationDataEntity configurationDataEntity) {
333         try (FileWriter fw = new FileWriter(
334                 PolicyController.getConfigHome() + File.separator + configurationDataEntity.getConfigurationName())) {
335             BufferedWriter bw = new BufferedWriter(fw);
336             bw.write(configurationDataEntity.getConfigBody());
337             bw.close();
338         } catch (IOException e) {
339             logger.error("Exception Occured While cloning the configuration file", e);
340         }
341     }
342
343     private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) {
344         try (FileWriter fw = new FileWriter(
345                 PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
346             BufferedWriter bw = new BufferedWriter(fw);
347             bw.write(actionBodyEntity.getActionBody());
348             bw.close();
349         } catch (IOException e) {
350             logger.error("Exception Occured While cloning the configuration file", e);
351         }
352     }
353
354     // return the column header name value
355     private String getCellHeaderName(Cell cell) {
356         return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
357     }
358
359     /**
360      * This is to validate all matching required fields.
361      *
362      * @param policyName String
363      * @param jsonString String
364      * @return String
365      */
366     public String validatMatchRequiredFields(String policyName, String jsonString) {
367
368         try {
369             JSONObject jsonObject = new JSONObject(jsonString);
370             String configName = jsonObject.getString("configName");
371             String uuid = jsonObject.getString("uuid");
372             String erorMsg = validConfigName(configName);
373             if (erorMsg != null) {
374                 return erorMsg;
375             }
376             erorMsg = validUuid(uuid);
377             if (erorMsg != null) {
378                 return erorMsg;
379             }
380             String location = jsonObject.getString("location");
381             erorMsg = validLocation(location);
382             if (erorMsg != null) {
383                 return erorMsg;
384             }
385             String policyScope = jsonObject.getString("policyScope");
386             erorMsg = validPolicyScope(policyScope);
387             if (erorMsg != null) {
388                 return erorMsg;
389             }
390             String msVersion = jsonObject.getString("version");
391             String msService = jsonObject.getString("service");
392             if (!isAttributeObjectFound(msService, msVersion)) {
393                 return POLICY + policyName + " MS Service: " + msService + " and MS Version: " + msVersion + NOTVALID;
394             }
395
396         } catch (Exception e) {
397             logger.error("Exception Occured While validating required fields", e);
398         }
399
400         return null;
401     }
402
403     private JSONObject validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
404             boolean configurationBodySet) {
405         if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) {
406             String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString());
407             if (errorMsg != null) {
408                 logger.error("errorMsg => " + errorMsg);
409                 JSONObject response = new JSONObject();
410                 response.append("error", errorMsg);
411                 return response;
412             }
413         }
414         return null;
415     }
416
417     private String validConfigName(String configName) {
418         String message = null;
419         if (configName != null) {
420             List<String> configNames = commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name");
421             if (configNames != null
422                     && (!(configNames.stream().filter(o -> o.equals(configName)).findFirst().isPresent()))) {
423                 message = POLICY + policyName + " configName: " + configName + NOTVALID;
424             }
425         } else {
426             message = POLICY + policyName + "configName is null";
427         }
428         return message;
429     }
430
431     private String validUuid(String uuid) {
432         String message = null;
433         if (uuid != null) {
434             List<String> uuids = commonClassDao.getDataByColumn(DCAEuuid.class, "name");
435             if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) {
436                 message = POLICY + policyName + " uuid: " + uuid + NOTVALID;
437             }
438         } else {
439             message = POLICY + policyName + "uuid is null";
440         }
441         return message;
442     }
443
444     private String validLocation(String location) {
445         String message = null;
446         if (location != null) {
447             List<String> locations = commonClassDao.getDataByColumn(MicroServiceLocation.class, "name");
448             if ((locations != null && !(locations.stream().filter(o -> o.equals(location)).findFirst().isPresent()))) {
449                 message = POLICY + policyName + " location: " + location + NOTVALID;
450             }
451         } else {
452             message = POLICY + policyName + "location is null";
453         }
454         return message;
455     }
456
457     private String validPolicyScope(String policyScope) {
458         String message = null;
459         if (policyScope != null) {
460             List<Object> foundData =
461                     commonClassDao.checkDuplicateEntry(policyScope, "groupList", GroupPolicyScopeList.class);
462             if (foundData == null || foundData.isEmpty()) {
463                 message = POLICY + policyName + " policyScope: " + policyScope + NOTVALID;
464             }
465         } else {
466             message = POLICY + policyName + "policyScope is null";
467         }
468         return message;
469     }
470
471     private boolean isAttributeObjectFound(String msService, String msVersion) {
472         if (msService == null) {
473             return false;
474         }
475
476         if (msVersion == null) {
477             return false;
478         }
479         MicroServiceModels workingModel = null;
480         List<Object> microServiceModelsData =
481                 commonClassDao.getDataById(MicroServiceModels.class, "modelName", msService);
482         if (microServiceModelsData != null) {
483             for (int i = 0; i < microServiceModelsData.size(); i++) {
484                 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
485                 if (workingModel != null && workingModel.getVersion() != null
486                         && workingModel.getVersion().equals(msVersion)) {
487                     return true;
488                 }
489             }
490         }
491         return false;
492     }
493
494     private PolicyEntity populatePolicyEntity(Cell cell, PolicyEntity policyEntityObject) {
495
496         if (policyEntityObject == null) {
497             return null;
498         }
499
500         PolicyEntity policyEntity = policyEntityObject;
501         if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
502             policyEntity.setScope(cell.getStringCellValue());
503         }
504         if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
505             policyEntity.setPolicyData(cell.getStringCellValue());
506         }
507         if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
508             policyEntity.setDescription(cell.getStringCellValue());
509         }
510
511         return policyEntity;
512     }
513
514     private void saveConfigurePolicy(String configName, ConfigurationDataEntity configurationDataEntity, String userId,
515             boolean configExists) {
516         if (configExists) {
517             if (configName.endsWith("json")) {
518                 configurationDataEntity.setConfigType("JSON");
519             } else if (configName.endsWith("txt")) {
520                 configurationDataEntity.setConfigType("OTHER");
521             } else if (configName.endsWith("xml")) {
522                 configurationDataEntity.setConfigType("XML");
523             } else if (configName.endsWith("properties")) {
524                 configurationDataEntity.setConfigType("PROPERTIES");
525             }
526             configurationDataEntity.setDeleted(false);
527             configurationDataEntity.setCreatedBy(userId);
528             configurationDataEntity.setModifiedBy(userId);
529             commonClassDao.save(configurationDataEntity);
530             writeConfigurationFile(configurationDataEntity);
531         }
532     }
533
534     private void saveActionPolicy(ActionBodyEntity actionBodyEntity, String userId, boolean actionExists) {
535         if (actionExists) {
536             actionBodyEntity.setDeleted(false);
537             actionBodyEntity.setCreatedBy(userId);
538             actionBodyEntity.setModifiedBy(userId);
539             commonClassDao.save(actionBodyEntity);
540             writeActionBodyFile(actionBodyEntity);
541         }
542     }
543
544     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo) {
545         if (roles.contains(superAdmin) || roles.contains(superEditor)) {
546             // 1. if Role contains super admin create scope.
547             // 2. if Role contains super editor don't create new scope and add to list to show to user.
548             PolicyEditorScopes policyEditorScope =
549                     (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
550             if (policyEditorScope == null) {
551                 if (roles.contains(superAdmin)) {
552                     PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
553                     policyEditorScopeEntity.setScopeName(scope);
554                     policyEditorScopeEntity.setUserCreatedBy(userInfo);
555                     policyEditorScopeEntity.setUserModifiedBy(userInfo);
556                     commonClassDao.save(policyEditorScopeEntity);
557                 } else {
558                     // Add Error Message a new Scope Exists, contact super-admin to create a new scope
559                     return true;
560                 }
561             }
562         }
563         return false;
564     }
565
566     @SuppressWarnings("rawtypes")
567     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
568         if (roles.contains(admin) || roles.contains(editor)) {
569             if (scopes.isEmpty()) {
570                 logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
571             } else {
572                 // 1. if Role contains admin, then check if parent scope has role admin, if not don't
573                 // create a scope and add to list.
574                 if (roles.contains(admin)) {
575                     String scopeCheck = scope.substring(0, scope.lastIndexOf('.'));
576                     if (scopes.contains(scopeCheck)) {
577                         PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
578                         policyEditorScopeEntity.setScopeName(scope);
579                         policyEditorScopeEntity.setUserCreatedBy(userInfo);
580                         policyEditorScopeEntity.setUserModifiedBy(userInfo);
581                         commonClassDao.save(policyEditorScopeEntity);
582                     } else {
583                         return true;
584                     }
585                 } else {
586                     return true;
587                 }
588             }
589         }
590         return false;
591     }
592
593     private boolean isContinue(List<Object> queryData, List<String> roles, String scope, UserInfo userInfo,
594             Set<String> scopes) {
595         if (!queryData.isEmpty()) {
596             return true;
597         }
598         if (isContinue(roles, scope, userInfo)) {
599             return true;
600         }
601         return isContinue(roles, scope, userInfo, scopes);
602     }
603
604     private void savePolicyEntity(PolicyEntity policyEntity, String configName, String userId) {
605         if (configName != null) {
606             if (configName.contains(config) || configName.contains(DECISION_MS)) {
607                 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao
608                         .getEntityItem(ConfigurationDataEntity.class, configurationName, configName);
609                 policyEntity.setConfigurationData(configuration);
610             } else {
611                 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class,
612                         "actionBodyName", configName);
613                 policyEntity.setActionBodyEntity(actionBody);
614             }
615         }
616         policyEntity.setCreatedBy(userId);
617         policyEntity.setModifiedBy(userId);
618         policyEntity.setDeleted(false);
619         commonClassDao.save(policyEntity);
620     }
621
622     private void saveVersion(PolicyEntity policyEntity, String scope, String userId) {
623         PolicyVersion policyVersion = new PolicyVersion();
624         String policyNamel = policyEntity.getPolicyName().replace(".xml", "");
625         int version = Integer.parseInt(policyNamel.substring(policyNamel.lastIndexOf('.') + 1));
626         policyNamel = policyNamel.substring(0, policyNamel.lastIndexOf('.'));
627
628         policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyNamel);
629         policyVersion.setActiveVersion(version);
630         policyVersion.setHigherVersion(version);
631         policyVersion.setCreatedBy(userId);
632         policyVersion.setModifiedBy(userId);
633         commonClassDao.save(policyVersion);
634     }
635
636     private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) {
637         int setBodySizel = setBodySize;
638         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
639                 && ((policyEntity.getPolicyName().contains(config)
640                         || policyEntity.getPolicyName().contains(DECISION_MS))
641                         && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
642             setBodySizel += 1;
643         }
644         return setBodySizel;
645     }
646
647     private boolean isFinalColumn(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
648             boolean finalColumn) {
649         boolean finalColumnl = finalColumn;
650         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
651                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
652                 && setBodySize == bodySize) {
653             finalColumnl = true;
654         }
655         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() < 1) {
656             finalColumnl = true;
657         }
658         return finalColumnl;
659     }
660
661     private boolean isConfigurationBodySet(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
662             boolean configurationBodySet) {
663         boolean configurationBodySetl = configurationBodySet;
664         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
665                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
666                 && (setBodySize == bodySize)) {
667             configurationBodySetl = true;
668         }
669         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
670                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
671                 && (setBodySize == 0)) {
672             configurationBodySetl = true;
673         }
674         return configurationBodySetl;
675     }
676
677     private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) {
678         boolean configExistsl = configExists;
679         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
680                 && (policyEntity.getPolicyName().contains(config)
681                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
682             configExistsl = true;
683         }
684         return configExistsl;
685     }
686
687     private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) {
688         boolean actionExistsl = actionExists;
689         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
690                 && policyEntity.getPolicyName().contains(ACTION)) {
691             actionExistsl = true;
692         }
693         return actionExistsl;
694     }
695
696     private int getBobySize(int bodySize, Cell cell) {
697         int bodySizel = bodySize;
698         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() >= 1) {
699             bodySizel = (int) cell.getNumericCellValue();
700         }
701         return bodySizel;
702     }
703
704     private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) {
705         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
706                 && (policyEntity.getPolicyName().contains(config)
707                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
708             body.append(cell.getStringCellValue());
709         }
710
711         return body;
712     }
713
714     private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
715             Cell cell) {
716         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
717                 && (policyEntity.getPolicyName().contains(ACTION))) {
718             actionBodyEntity.setActionBody(cell.getStringCellValue());
719         }
720         return actionBodyEntity;
721     }
722
723     private ActionBodyEntity populateActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
724             Cell cell) {
725         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
726                 && policyEntity.getPolicyName().contains(ACTION)) {
727             actionBodyEntity.setActionBodyName(cell.getStringCellValue());
728         }
729         return actionBodyEntity;
730     }
731
732     private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity,
733             ConfigurationDataEntity configurationDataEntity, Cell cell) {
734         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
735                 && (policyEntity.getPolicyName().contains(config)
736                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
737             configurationDataEntity.setConfigurationName(cell.getStringCellValue());
738         }
739         return configurationDataEntity;
740     }
741
742     private String getConfigName(Cell cell, String configName) {
743         String configNameL = configName;
744         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))) {
745             configNameL = cell.getStringCellValue();
746         }
747         return configNameL;
748     }
749
750     private void savePolicyEntiies(boolean finalColumn, boolean configurationBodySet,
751             ConfigurationDataEntity configurationDataEntity, PolicyEntity policyEntity, PolicyController controller,
752             List<String> roles, UserInfo userInfo, Set<String> scopes, String configName, String userId,
753             boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body) {
754
755         if (finalColumn && configurationBodySet) {
756             configurationDataEntity.setConfigBody(body.toString());
757             String scope = policyEntity.getScope().replace(".", File.separator);
758             String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
759             SimpleBindings params = new SimpleBindings();
760             params.put(policyName, policyEntity.getPolicyName());
761             params.put("policyScope", policyEntity.getScope());
762             List<Object> queryData = controller.getDataByQuery(query, params);
763
764             if (isContinue(queryData, roles, scope, userInfo, scopes)) {
765                 return;
766             }
767             saveConfigurePolicy(configName, configurationDataEntity, userId, configExists); //
768             saveActionPolicy(actionBodyEntity, userId, actionExists); //
769             savePolicyEntity(policyEntity, configName, userId);//
770             saveVersion(policyEntity, scope, userId); //
771             // Notify Other paps regarding Export Policy.
772             PolicyRestController restController = new PolicyRestController();
773             restController.notifyOtherPapsToUpdateConfigurations("exportPolicy", configName, null);
774         }
775     }
776 }