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