6c7a0aff3b9b2cf506ffc6c40024a1898b7217b9
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
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 import java.io.BufferedWriter;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.PrintWriter;
33 import java.util.ArrayList;
34 import java.util.Iterator;
35 import java.util.LinkedHashMap;
36 import java.util.List;
37 import java.util.Set;
38 import javax.script.SimpleBindings;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import org.apache.poi.hssf.usermodel.HSSFRow;
42 import org.apache.poi.hssf.usermodel.HSSFSheet;
43 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
44 import org.apache.poi.ss.usermodel.Cell;
45 import org.apache.poi.ss.usermodel.Row;
46 import org.apache.poi.ss.usermodel.Sheet;
47 import org.json.JSONObject;
48 import org.onap.policy.admin.PolicyRestController;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.rest.adapter.PolicyExportAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.ActionBodyEntity;
54 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
55 import org.onap.policy.rest.jpa.DCAEuuid;
56 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
57 import org.onap.policy.rest.jpa.MicroServiceConfigName;
58 import org.onap.policy.rest.jpa.MicroServiceLocation;
59 import org.onap.policy.rest.jpa.MicroServiceModels;
60 import org.onap.policy.rest.jpa.PolicyEditorScopes;
61 import org.onap.policy.rest.jpa.PolicyEntity;
62 import org.onap.policy.rest.jpa.PolicyVersion;
63 import org.onap.policy.rest.jpa.UserInfo;
64 import org.onap.policy.utils.UserUtils.Pair;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.portalsdk.core.controller.RestrictedBaseController;
67 import org.onap.portalsdk.core.web.support.UserUtils;
68 import org.springframework.stereotype.Controller;
69 import org.springframework.web.bind.annotation.RequestMapping;
70
71 @Controller
72 @RequestMapping("/")
73 public class PolicyExportAndImportController extends RestrictedBaseController {
74
75     private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
76
77     private static String superAdmin = "super-admin";
78     private static String superEditor = "super-editor";
79     private static String admin = "admin";
80     private static String editor = "editor";
81     private static String policyName = "policyName";
82     private static String configurationName = "configurationName";
83     private static String configurationbody = "configurationbody";
84     private static String config = "Config_";
85     private static final String CONFIG_MS = "Config_MS_";
86     private static final String NOTVALID = " is not valid.";
87     private static final String POLICY = "Policy:";
88     private static final String BODYSIZE = "bodySize";
89     private static final String DECISION_MS = "Decision_MS_";
90     private static final String ACTION = "Action_";
91     private static CommonClassDao commonClassDao;
92
93
94     private PolicyController policyController;
95
96     public PolicyController getPolicyController() {
97         return policyController;
98     }
99
100     public void setPolicyController(PolicyController policyController) {
101         this.policyController = policyController;
102     }
103
104     public static CommonClassDao getCommonClassDao() {
105         return commonClassDao;
106     }
107
108     public static void setCommonClassDao(CommonClassDao commonClassDao) {
109         PolicyExportAndImportController.commonClassDao = commonClassDao;
110     }
111
112     public PolicyExportAndImportController() {
113         // Empty constructor
114     }
115
116     /**
117      * This is for downloading existing policy.
118      * 
119      * @param request HttpServletRequest
120      * @param response HttpServletResponse
121      * @throws IOException error out
122      */
123     @RequestMapping(value = {"/policy_download/exportPolicy.htm"},
124             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
125     public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
126         try (HSSFWorkbook workBook2 = new HSSFWorkbook()) {
127             ArrayList<String> selectedPolicy = new ArrayList<>();
128             ObjectMapper mapper = new ObjectMapper();
129             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
130             JsonNode root = mapper.readTree(request.getReader());
131             PolicyExportAdapter adapter =
132                     mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
133             for (Object policyId : adapter.getPolicyDatas()) {
134                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
135                 String policyWithScope =
136                         selected.get(policyName).toString() + "." + selected.get("activeVersion").toString() + ".xml";
137                 String scope =
138                         policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator)).replace(
139                                 File.separator, ".");
140                 String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1);
141                 selectedPolicy.add(policyNamel + ":" + scope);
142             }
143
144             HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
145             HSSFRow headingRow = sheet.createRow(0);
146             headingRow.createCell(0).setCellValue(policyName);
147             headingRow.createCell(1).setCellValue("scope");
148             headingRow.createCell(2).setCellValue("version");
149             headingRow.createCell(3).setCellValue("policyData");
150             headingRow.createCell(4).setCellValue("description");
151             headingRow.createCell(5).setCellValue(configurationName);
152             headingRow.createCell(6).setCellValue(BODYSIZE);
153             headingRow.createCell(7).setCellValue(configurationbody);
154
155             List<Object> entityData =
156                     commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope",
157                             selectedPolicy);
158             processEntityData(entityData, sheet, headingRow); //
159             String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
160             String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
161             File deleteCheck = new File(deleteCheckPath);
162             if (deleteCheck.exists() && deleteCheck.delete()) {
163                 logger.info("Deleted the file from system before exporting a new file.");
164             }
165             File temPath = new File(tmp);
166             if (!temPath.exists()) {
167                 temPath.mkdir();
168             }
169
170             String file = temPath + File.separator + "PolicyExport.xls";
171             File filepath = new File(file);
172             FileOutputStream fos = new FileOutputStream(filepath);
173             workBook2.write(fos);
174             fos.flush();
175
176             response.setContentType("application / json");
177             request.setCharacterEncoding("UTF-8");
178
179             PrintWriter out = response.getWriter();
180             String successMap = file.substring(file.lastIndexOf("webapps") + 8);
181             String responseString = mapper.writeValueAsString(successMap);
182             JSONObject j = new JSONObject("{data: " + responseString + "}");
183             out.write(j.toString());
184         } catch (Exception e) {
185             logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e);
186         }
187     }
188
189     private void processEntityData(List<Object> entityData, HSSFSheet sheet, HSSFRow headingRow) {
190
191         short rowNo = 1;
192         for (Object object : entityData) {
193             PolicyEntity policyEntity = (PolicyEntity) object;
194             HSSFRow row = sheet.createRow(rowNo);
195             row.createCell(0).setCellValue(policyEntity.getPolicyName());
196             row.createCell(1).setCellValue(policyEntity.getScope());
197             row.createCell(2).setCellValue(policyEntity.getVersion());
198             row.createCell(3).setCellValue(policyEntity.getPolicyData());
199             row.createCell(4).setCellValue(policyEntity.getDescription());
200             if (policyEntity.getPolicyName().contains(DECISION_MS)
201                     || !policyEntity.getPolicyName().contains("Decision_")) {
202                 if (policyEntity.getConfigurationData() != null) {
203                     row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
204                     String body = policyEntity.getConfigurationData().getConfigBody();
205                     row = populateConfigParam(policyEntity, row, headingRow, body);
206                 }
207                 populateActionBodyEntity(policyEntity, row);
208             } else {
209                 row.createCell(5).setCellValue("");
210                 row.createCell(6).setCellValue(0);
211                 row.createCell(7).setCellValue("");
212             }
213             rowNo++;
214         }
215     }
216
217     private HSSFRow populateActionBodyEntity(PolicyEntity policyEntity, HSSFRow row) {
218         if (policyEntity.getActionBodyEntity() != null) {
219             row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
220             row.createCell(6).setCellValue(0);
221             row.createCell(7).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
222         }
223         return row;
224     }
225
226     private HSSFRow populateConfigParam(PolicyEntity policyEntity, HSSFRow row, HSSFRow headingRow, String body) {
227
228         if (policyEntity.getPolicyName().contains("Config_BRMS_Param_")) {
229             int index = 0;
230             int arraySize = 0;
231             while (index < body.length()) {
232                 if (arraySize == 0) {
233                     row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
234                 } else {
235                     headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize);
236                     row.createCell(7 + arraySize).setCellValue(
237                             body.substring(index, Math.min(index + 30000, body.length())));
238                 }
239                 index += 30000;
240                 arraySize += 1;
241             }
242             row.createCell(6).setCellValue(arraySize);
243         } else {
244             row.createCell(6).setCellValue(0);
245             row.createCell(7).setCellValue(body);
246         }
247         return row;
248     }
249
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.u;
273         Set<String> scopes = pair.t;
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 =
335                 new FileWriter(PolicyController.getConfigHome() + File.separator
336                         + configurationDataEntity.getConfigurationName())) {
337             BufferedWriter bw = new BufferedWriter(fw);
338             bw.write(configurationDataEntity.getConfigBody());
339             bw.close();
340         } catch (IOException e) {
341             logger.error("Exception Occured While cloning the configuration file", e);
342         }
343     }
344
345     private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) {
346         try (FileWriter fw =
347              new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
348             BufferedWriter bw = new BufferedWriter(fw);
349             bw.write(actionBodyEntity.getActionBody());
350             bw.close();
351         } catch (IOException e) {
352             logger.error("Exception Occured While cloning the configuration file", e);
353         }
354     }
355
356     // return the column header name value
357     private String getCellHeaderName(Cell cell) {
358         return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
359     }
360
361     /**
362      * This is to validate all matching required fields.
363      * 
364      * @param policyName String
365      * @param jsonString String
366      * @return String
367      */
368     public String validatMatchRequiredFields(String policyName, String jsonString) {
369
370         try {
371             JSONObject jsonObject = new JSONObject(jsonString);
372             String configName = jsonObject.getString("configName");
373             String uuid = jsonObject.getString("uuid");
374             String erorMsg = validConfigName(configName);
375             if (erorMsg != null) {
376                 return erorMsg;
377             }
378             erorMsg = validUuid(uuid);
379             if (erorMsg != null) {
380                 return erorMsg;
381             }
382             String location = jsonObject.getString("location");
383             erorMsg = validLocation(location);
384             if (erorMsg != null) {
385                 return erorMsg;
386             }
387             String policyScope = jsonObject.getString("policyScope");
388             erorMsg = validPolicyScope(policyScope);
389             if (erorMsg != null) {
390                 return erorMsg;
391             }
392             String msVersion = jsonObject.getString("version");
393             String msService = jsonObject.getString("service");
394             if (!isAttributeObjectFound(msService, msVersion)) {
395                 return POLICY + policyName + " MS Service: " + msService + " and MS Version: " + msVersion + NOTVALID;
396             }
397
398         } catch (Exception e) {
399             logger.error("Exception Occured While validating required fields", e);
400         }
401
402         return null;
403     }
404
405     private JSONObject validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
406             boolean configurationBodySet) {
407         if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) {
408             String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString());
409             if (errorMsg != null) {
410                 logger.error("errorMsg => " + errorMsg);
411                 JSONObject response = new JSONObject();
412                 response.append("error", errorMsg);
413                 return response;
414             }
415         }
416         return null;
417     }
418
419     private String validConfigName(String configName) {
420         String message = null;
421         if (configName != null) {
422             List<String> configNames = commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name");
423             if (configNames != null
424                     && (!(configNames.stream().filter(o -> o.equals(configName)).findFirst().isPresent()))) {
425                 message = POLICY + policyName + " configName: " + configName + NOTVALID;
426             }
427         } else {
428             message = POLICY + policyName + "configName is null";
429         }
430         return message;
431     }
432
433     private String validUuid(String uuid) {
434         String message = null;
435         if (uuid != null) {
436             List<String> uuids = commonClassDao.getDataByColumn(DCAEuuid.class, "name");
437             if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) {
438                 message = POLICY + policyName + " uuid: " + uuid + NOTVALID;
439             }
440         } else {
441             message = POLICY + policyName + "uuid is null";
442         }
443         return message;
444     }
445
446     private String validLocation(String location) {
447         String message = null;
448         if (location != null) {
449             List<String> locations = commonClassDao.getDataByColumn(MicroServiceLocation.class, "name");
450             if ((locations != null && !(locations.stream().filter(o -> o.equals(location)).findFirst().isPresent()))) {
451                 message = POLICY + policyName + " location: " + location + NOTVALID;
452             }
453         } else {
454             message = POLICY + policyName + "location is null";
455         }
456         return message;
457     }
458
459     private String validPolicyScope(String policyScope) {
460         String message = null;
461         if (policyScope != null) {
462             List<Object> foundData =
463                     commonClassDao.checkDuplicateEntry(policyScope, "groupList", GroupPolicyScopeList.class);
464             if (foundData == null || foundData.isEmpty()) {
465                 message = POLICY + policyName + " policyScope: " + policyScope + NOTVALID;
466             }
467         } else {
468             message = POLICY + policyName + "policyScope is null";
469         }
470         return message;
471     }
472
473     private boolean isAttributeObjectFound(String msService, String msVersion) {
474         if (msService == null) {
475             return false;
476         }
477
478         if (msVersion == null) {
479             return false;
480         }
481         MicroServiceModels workingModel = null;
482         List<Object> microServiceModelsData =
483                 commonClassDao.getDataById(MicroServiceModels.class, "modelName", msService);
484         if (microServiceModelsData != null) {
485             for (int i = 0; i < microServiceModelsData.size(); i++) {
486                 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
487                 if (workingModel != null && workingModel.getVersion() != null
488                         && workingModel.getVersion().equals(msVersion)) {
489                     return true;
490                 }
491             }
492         }
493         return false;
494     }
495
496     private PolicyEntity populatePolicyEntity(Cell cell, PolicyEntity policyEntityObject) {
497
498         if (policyEntityObject == null) {
499             return null;
500         }
501
502         PolicyEntity policyEntity = policyEntityObject;
503         if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
504             policyEntity.setScope(cell.getStringCellValue());
505         }
506         if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
507             policyEntity.setPolicyData(cell.getStringCellValue());
508         }
509         if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
510             policyEntity.setDescription(cell.getStringCellValue());
511         }
512
513         return policyEntity;
514     }
515
516     private void saveConfigurePolicy(String configName, ConfigurationDataEntity configurationDataEntity, String userId,
517             boolean configExists) {
518         if (configExists) {
519             if (configName.endsWith("json")) {
520                 configurationDataEntity.setConfigType("JSON");
521             } else if (configName.endsWith("txt")) {
522                 configurationDataEntity.setConfigType("OTHER");
523             } else if (configName.endsWith("xml")) {
524                 configurationDataEntity.setConfigType("XML");
525             } else if (configName.endsWith("properties")) {
526                 configurationDataEntity.setConfigType("PROPERTIES");
527             }
528             configurationDataEntity.setDeleted(false);
529             configurationDataEntity.setCreatedBy(userId);
530             configurationDataEntity.setModifiedBy(userId);
531             commonClassDao.save(configurationDataEntity);
532             writeConfigurationFile(configurationDataEntity);
533         }
534     }
535
536     private void saveActionPolicy(ActionBodyEntity actionBodyEntity, String userId, boolean actionExists) {
537         if (actionExists) {
538             actionBodyEntity.setDeleted(false);
539             actionBodyEntity.setCreatedBy(userId);
540             actionBodyEntity.setModifiedBy(userId);
541             commonClassDao.save(actionBodyEntity);
542             writeActionBodyFile(actionBodyEntity);
543         }
544     }
545
546     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo) {
547         if (roles.contains(superAdmin) || roles.contains(superEditor)) {
548             // 1. if Role contains super admin create scope.
549             // 2. if Role contains super editor don't create new scope and add to list to show to user.
550             PolicyEditorScopes policyEditorScope =
551                     (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
552             if (policyEditorScope == null) {
553                 if (roles.contains(superAdmin)) {
554                     PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
555                     policyEditorScopeEntity.setScopeName(scope);
556                     policyEditorScopeEntity.setUserCreatedBy(userInfo);
557                     policyEditorScopeEntity.setUserModifiedBy(userInfo);
558                     commonClassDao.save(policyEditorScopeEntity);
559                 } else {
560                     // Add Error Message a new Scope Exists, contact super-admin to create a new scope
561                     return true;
562                 }
563             }
564         }
565         return false;
566     }
567
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 =
609                         (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class,
610                                 configurationName, configName);
611                 policyEntity.setConfigurationData(configuration);
612             } else {
613                 ActionBodyEntity actionBody =
614                         (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName",
615                                 configName);
616                 policyEntity.setActionBodyEntity(actionBody);
617             }
618         }
619         policyEntity.setCreatedBy(userId);
620         policyEntity.setModifiedBy(userId);
621         policyEntity.setDeleted(false);
622         commonClassDao.save(policyEntity);
623     }
624
625     private void saveVersion(PolicyEntity policyEntity, String scope, String userId) {
626         PolicyVersion policyVersion = new PolicyVersion();
627         String policyNamel = policyEntity.getPolicyName().replace(".xml", "");
628         int version = Integer.parseInt(policyNamel.substring(policyNamel.lastIndexOf('.') + 1));
629         policyNamel = policyNamel.substring(0, policyNamel.lastIndexOf('.'));
630
631         policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyNamel);
632         policyVersion.setActiveVersion(version);
633         policyVersion.setHigherVersion(version);
634         policyVersion.setCreatedBy(userId);
635         policyVersion.setModifiedBy(userId);
636         commonClassDao.save(policyVersion);
637     }
638
639     private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) {
640         int setBodySizel = setBodySize;
641         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
642                 && ((policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName()
643                         .contains(DECISION_MS)) && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
644             setBodySizel += 1;
645         }
646         return setBodySizel;
647     }
648
649     private boolean isFinalColumn(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
650             boolean finalColumn) {
651         boolean finalColumnl = finalColumn;
652         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
653                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
654                 && setBodySize == bodySize) {
655             finalColumnl = true;
656         }
657         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() < 1) {
658             finalColumnl = true;
659         }
660         return finalColumnl;
661     }
662
663     private boolean isConfigurationBodySet(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
664             boolean configurationBodySet) {
665         boolean configurationBodySetl = configurationBodySet;
666         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
667             && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS)) 
668             && (setBodySize == bodySize)) {
669             configurationBodySetl = true;
670         }
671         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
672             && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
673             && (setBodySize == 0)) {
674             configurationBodySetl = true;
675         }
676         return configurationBodySetl;
677     }
678
679
680     private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) {
681         boolean configExistsl = configExists;
682         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
683             && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
684             configExistsl = true;
685         }
686         return configExistsl;
687     }
688
689
690     private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) {
691         boolean actionExistsl = actionExists;
692         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
693                 && policyEntity.getPolicyName().contains(ACTION)) {
694             actionExistsl = true;
695         }
696         return actionExistsl;
697     }
698
699     private int getBobySize(int bodySize, Cell cell) {
700         int bodySizel = bodySize;
701         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() >= 1) {
702             bodySizel = (int) cell.getNumericCellValue();
703         }
704         return bodySizel;
705     }
706
707     private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) {
708         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
709             && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
710             body.append(cell.getStringCellValue());
711         }
712
713         return body;
714     }
715
716     private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity, 
717             Cell cell) {
718         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
719             && (policyEntity.getPolicyName().contains(ACTION))) {
720             actionBodyEntity.setActionBody(cell.getStringCellValue());
721         }
722         return actionBodyEntity;
723     }
724
725     private ActionBodyEntity populateActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
726             Cell cell) {
727         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
728                 && policyEntity.getPolicyName().contains(ACTION)) {
729             actionBodyEntity.setActionBodyName(cell.getStringCellValue());
730         }
731         return actionBodyEntity;
732     }
733
734     private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity,
735             ConfigurationDataEntity configurationDataEntity, Cell cell) {
736         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
737             && (policyEntity.getPolicyName().contains(config) || 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 }