2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.admin;
24 import java.io.BufferedReader;
25 import java.io.BufferedWriter;
26 import java.io.ByteArrayInputStream;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.nio.charset.StandardCharsets;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
41 import javax.json.Json;
42 import javax.json.JsonArray;
43 import javax.json.JsonReader;
44 import javax.script.SimpleBindings;
45 import javax.servlet.ServletConfig;
46 import javax.servlet.ServletException;
47 import javax.servlet.annotation.WebInitParam;
48 import javax.servlet.annotation.WebServlet;
49 import javax.servlet.http.HttpServlet;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
53 import org.apache.commons.compress.utils.IOUtils;
54 import org.apache.commons.fileupload.FileItem;
55 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
56 import org.apache.commons.fileupload.servlet.ServletFileUpload;
57 import org.apache.http.HttpStatus;
58 import org.json.JSONArray;
59 import org.json.JSONException;
60 import org.json.JSONObject;
61 import org.onap.policy.common.logging.flexlogger.FlexLogger;
62 import org.onap.policy.common.logging.flexlogger.Logger;
63 import org.onap.policy.components.HumanPolicyComponent;
64 import org.onap.policy.controller.PolicyController;
65 import org.onap.policy.controller.PolicyExportAndImportController;
66 import org.onap.policy.rest.XACMLRest;
67 import org.onap.policy.rest.XACMLRestProperties;
68 import org.onap.policy.rest.adapter.PolicyRestAdapter;
69 import org.onap.policy.rest.jpa.ActionBodyEntity;
70 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
71 import org.onap.policy.rest.jpa.PolicyEditorScopes;
72 import org.onap.policy.rest.jpa.PolicyEntity;
73 import org.onap.policy.rest.jpa.PolicyVersion;
74 import org.onap.policy.rest.jpa.UserInfo;
75 import org.onap.policy.utils.PolicyUtils;
76 import org.onap.policy.utils.UserUtils.Pair;
77 import org.onap.policy.xacml.api.XACMLErrorConstants;
78 import org.onap.policy.xacml.util.XACMLPolicyScanner;
79 import org.onap.portalsdk.core.web.support.UserUtils;
81 import com.att.research.xacml.util.XACMLProperties;
82 import com.fasterxml.jackson.databind.JsonNode;
83 import com.fasterxml.jackson.databind.ObjectMapper;
85 @WebServlet(value = "/fm/*", loadOnStartup = 1, initParams = {
86 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
87 public class PolicyManagerServlet extends HttpServlet {
88 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
89 private static final long serialVersionUID = -8453502699403909016L;
90 private static final String VERSION = "version";
91 private static final String NAME = "name";
92 private static final String DATE = "date";
93 private static final String SIZE = "size";
94 private static final String TYPE = "type";
95 private static final String ROLETYPE = "roleType";
96 private static final String CREATED_BY = "createdBy";
97 private static final String MODIFIED_BY = "modifiedBy";
98 private static final String CONTENTTYPE = "application/json";
99 private static final String SUPERADMIN = "super-admin";
100 private static final String SUPEREDITOR = "super-editor";
101 private static final String SUPERGUEST = "super-guest";
102 private static final String ADMIN = "admin";
103 private static final String EDITOR = "editor";
104 private static final String GUEST = "guest";
105 private static final String RESULT = "result";
106 private static final String DELETE = "delete";
107 private static final String EXCEPTION_OCCURED = "Exception Occured";
108 private static final String CONFIG = ".Config_";
109 private static final String CONFIG1 = ":Config_";
110 private static final String ACTION = ".Action_";
111 private static final String ACTION1 = ":Action_";
112 private static final String DECISION = ".Decision_";
113 private static final String DECISION1 = ":Decision_";
114 private static final String CONFIG2 = "Config_";
115 private static final String ACTION2 = "Action_";
116 private static final String DECISION2 = "Decision_";
117 private static final String FORWARD_SLASH = "/";
118 private static final String BACKSLASH = "\\";
119 private static final String ESCAPE_BACKSLASH = "\\\\";
120 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
121 private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = "delete from PolicyVersion where policy_name ='";
122 private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
123 private static final String SPLIT_1 = "split_1";
124 private static final String SPLIT_0 = "split_0";
125 private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName";
126 private static final String SCOPE_NAME = "scopeName";
127 private static final String SUCCESS = "success";
128 private static final String SUB_SCOPENAME = "subScopename";
129 private static final String ALLSCOPES = "@All@";
130 private static final String PERCENT_AND_ID_GT_0 = "%' and id >0";
131 private static List<String> serviceTypeNamesList = new ArrayList<>();
132 private static JsonArray policyNames;
133 private static String testUserId = null;
136 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION,
140 private static PolicyController policyController;
142 private synchronized PolicyController getPolicyController() {
143 return policyController;
146 public static synchronized void setPolicyController(PolicyController policyController) {
147 PolicyManagerServlet.policyController = policyController;
150 public static JsonArray getPolicyNames() {
154 public static void setPolicyNames(JsonArray policyNames) {
155 PolicyManagerServlet.policyNames = policyNames;
158 public static List<String> getServiceTypeNamesList() {
159 return serviceTypeNamesList;
163 public void init(ServletConfig servletConfig) throws ServletException {
164 super.init(servletConfig);
166 // Common initialization
168 XACMLRest.xacmlInit(servletConfig);
170 // Initialize ClosedLoop JSON
172 PolicyManagerServlet.initializeJSONLoad();
175 private static void initializeJSONLoad() {
176 Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
177 String location = closedLoopJsonLocation.toString();
178 if (!location.endsWith("json")) {
179 LOGGER.warn("JSONConfig file does not end with extension .json");
182 try (FileInputStream inputStream = new FileInputStream(location);
183 JsonReader jsonReader = Json.createReader(inputStream)) {
184 policyNames = jsonReader.readArray();
185 serviceTypeNamesList = new ArrayList<>();
186 for (int i = 0; i < policyNames.size(); i++) {
187 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
188 String name = policyName.getJsonString("serviceTypePolicyName").getString();
189 serviceTypeNamesList.add(name);
191 } catch (IOException e) {
192 LOGGER.error("Exception Occured while initializing the JSONConfig file" + e);
197 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
198 LOGGER.debug("doPost");
200 // if request contains multipart-form-data
201 if (ServletFileUpload.isMultipartContent(request)) {
202 uploadFile(request, response);
204 // all other post request has json params in body
206 fileOperation(request, response);
208 } catch (Exception e) {
210 setError(e, response);
211 } catch (Exception e1) {
212 LOGGER.error(EXCEPTION_OCCURED + e1);
217 // Set Error Message for Exception
218 private void setError(Exception t, HttpServletResponse response) throws IOException {
220 JSONObject responseJsonObject = error(t.getMessage());
221 response.setContentType(CONTENTTYPE);
222 PrintWriter out = response.getWriter();
223 out.print(responseJsonObject);
225 } catch (Exception x) {
226 LOGGER.error(EXCEPTION_OCCURED + x);
227 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
231 // Policy Import Functionality
232 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
234 Map<String, InputStream> files = new HashMap<>();
236 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
237 for (FileItem item : items) {
238 if (!item.isFormField()) {
239 // Process form file field (input type="file").
240 files.put(item.getName(), item.getInputStream());
241 processFormFile(request, item);
245 JSONObject responseJsonObject;
246 responseJsonObject = this.success();
247 response.setContentType(CONTENTTYPE);
248 PrintWriter out = response.getWriter();
249 out.print(responseJsonObject);
251 } catch (Exception e) {
252 LOGGER.debug("Cannot write file");
253 throw new ServletException("Cannot write file", e);
257 private void processFormFile(HttpServletRequest request, FileItem item) {
259 if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
260 File file = new File(item.getName());
261 try (OutputStream outputStream = new FileOutputStream(file)) {
262 IOUtils.copy(item.getInputStream(), outputStream);
263 newFile = file.toString();
264 PolicyExportAndImportController importController = new PolicyExportAndImportController();
265 importController.importRepositoryFile(newFile, request);
266 } catch (Exception e) {
267 LOGGER.error("Upload error : " + e);
269 } else if (!item.getName().endsWith(".xls")) {
270 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
271 } else { // uploaded file size is greater than allowed
272 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
276 // File Operation Functionality
277 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
278 JSONObject responseJsonObject;
279 StringBuilder sb = new StringBuilder();
280 try (BufferedReader br = request.getReader()) {
282 while ((str = br.readLine()) != null) {
285 } catch (Exception e) {
286 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
287 responseJsonObject = error(e.getMessage());
288 setResponse(response, responseJsonObject);
292 JSONObject jObj = new JSONObject(sb.toString());
293 JSONObject params = jObj.getJSONObject("params");
294 Mode mode = Mode.valueOf(params.getString("mode"));
296 String userId = UserUtils.getUserSession(request).getOrgUserId();
298 "****************************************Logging UserID while doing actions on Editor tab*******************************************");
300 "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
302 "***********************************************************************************************************************************");
303 responseJsonObject = operateBasedOnMode(mode, params, request);
304 } catch (Exception e) {
305 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
306 responseJsonObject = error(e.getMessage());
308 setResponse(response, responseJsonObject);
311 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
312 response.setContentType(CONTENTTYPE);
313 try (PrintWriter out = response.getWriter()) {
314 out.print(responseJsonObject);
316 } catch (IOException e) {
317 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
321 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request)
322 throws ServletException {
323 JSONObject responseJsonObject;
327 responseJsonObject = addFolder(params, request);
330 responseJsonObject = copy(params, request);
333 responseJsonObject = delete(params, request);
337 responseJsonObject = editFile(params);
340 responseJsonObject = list(params, request);
343 responseJsonObject = rename(params, request);
345 case DESCRIBEPOLICYFILE:
346 responseJsonObject = describePolicy(params);
349 responseJsonObject = switchVersion(params, request);
352 responseJsonObject = searchPolicyList(params, request);
355 throw new ServletException("not implemented");
357 if (responseJsonObject == null) {
358 responseJsonObject = error("generic error : responseJsonObject is null");
360 return responseJsonObject;
363 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
364 List<Object> policyData = new ArrayList<>();
365 JSONArray policyList = null;
366 if (params.has("policyList")) {
367 policyList = (JSONArray) params.get("policyList");
369 PolicyController controller = getPolicyControllerInstance();
370 List<JSONObject> resultList = new ArrayList<>();
372 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
373 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
375 } catch (Exception e) {
377 "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
380 return new JSONObject().put(RESULT, resultList);
383 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
384 PolicyController controller, List<JSONObject> resultList) {
386 Set<String> scopes;// Get the Login Id of the User from Request
387 String userId = UserUtils.getUserSession(request).getOrgUserId();
388 List<Object> userRoles = controller.getRoles(userId);
389 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
392 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
393 if (scopes.isEmpty()) {
396 Set<String> tempScopes = scopes;
397 for (String scope : tempScopes) {
398 addScope(scopes, scope);
401 if (policyList != null) {
402 for (int i = 0; i < policyList.length(); i++) {
403 String policyName = policyList.get(i).toString().replace(".xml", "");
404 String version = policyName.substring(policyName.lastIndexOf('.') + 1);
405 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
406 parsePolicyList(resultList, controller, policyName, version);
409 getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
414 private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller,
415 List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
416 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
417 policyData = controller.getData(PolicyVersion.class);
419 List<Object> filterdatas = controller.getData(PolicyVersion.class);
420 for (Object filter : filterdatas) {
421 addFilterData(policyData, scopes, (PolicyVersion) filter);
425 if (!policyData.isEmpty()) {
426 updateResultList(policyData, resultList);
430 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
432 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
433 if (scopes.contains(scopeName)) {
434 policyData.add(filter);
436 } catch (Exception e) {
437 LOGGER.error("Exception occured while filtering policyversion data" + e);
441 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
442 for (Object aPolicyData : policyData) {
443 PolicyVersion policy = (PolicyVersion) aPolicyData;
444 JSONObject el = new JSONObject();
445 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
446 el.put(DATE, policy.getModifiedDate());
447 el.put(VERSION, policy.getActiveVersion());
449 el.put(TYPE, "file");
450 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
451 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
456 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName,
458 if (policyName.contains(BACKSLASH)) {
459 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
461 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
462 SimpleBindings pvParams = new SimpleBindings();
463 pvParams.put("policyName", policyName);
464 pvParams.put(VERSION, version);
465 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
466 if (!activeData.isEmpty()) {
467 PolicyVersion policy = (PolicyVersion) activeData.get(0);
468 JSONObject el = new JSONObject();
469 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
470 el.put(DATE, policy.getModifiedDate());
471 el.put(VERSION, policy.getActiveVersion());
473 el.put(TYPE, "file");
474 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
475 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
480 private void addScope(Set<String> scopes, String scope) {
481 List<Object> scopesList = queryPolicyEditorScopes(scope);
482 if (!scopesList.isEmpty()) {
483 for (Object aScopesList : scopesList) {
484 PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
485 scopes.add(tempScope.getScopeName());
490 // Switch Version Functionality
491 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException {
492 String path = params.getString("path");
493 String userId = null;
495 userId = UserUtils.getUserSession(request).getOrgUserId();
496 } catch (Exception e) {
497 LOGGER.error("Exception Occured while reading userid from cookie" + e);
500 String removeExtension = path.replace(".xml", "");
501 if (path.startsWith(FORWARD_SLASH)) {
502 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
504 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
508 PolicyController controller = getPolicyControllerInstance();
509 if (!params.toString().contains("activeVersion")) {
510 return controller.switchVersionPolicyContent(policyName);
512 String activeVersion = params.getString("activeVersion");
513 String highestVersion = params.get("highestVersion").toString();
514 if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) {
515 return error("The Version shouldn't be greater than Highest Value");
517 activePolicy = policyName + "." + activeVersion + ".xml";
518 String[] splitDBCheckName = modifyPolicyName(activePolicy);
519 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
520 SimpleBindings policyParams = new SimpleBindings();
521 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
522 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
523 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
524 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
525 if (pentity.isDeleted()) {
526 return error("The Policy is Not Existing in Workspace");
528 if (policyName.contains(FORWARD_SLASH)) {
529 policyName = policyName.replace(FORWARD_SLASH, File.separator);
531 policyName = policyName.substring(policyName.indexOf(File.separator) + 1);
532 if (policyName.contains(BACKSLASH)) {
533 policyName = policyName.replace(File.separator, BACKSLASH);
535 policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName;
536 String watchPolicyName = policyName;
537 if (policyName.contains(FORWARD_SLASH)) {
538 policyName = policyName.replace(FORWARD_SLASH, File.separator);
540 if (policyName.contains(BACKSLASH)) {
541 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
543 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName
545 // query the database
546 controller.executeQuery(query);
547 // Policy Notification
548 PolicyVersion entity = new PolicyVersion();
549 entity.setPolicyName(watchPolicyName);
550 entity.setActiveVersion(Integer.parseInt(activeVersion));
551 entity.setModifiedBy(userId);
552 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
557 private JSONObject describePolicy(JSONObject params) throws ServletException {
559 String path = params.getString("path");
561 if (path.startsWith(FORWARD_SLASH)) {
562 path = path.substring(1);
563 policyName = path.substring(path.lastIndexOf('/') + 1);
564 path = path.replace(FORWARD_SLASH, ".");
566 path = path.replace(FORWARD_SLASH, ".");
569 if (path.contains(CONFIG2)) {
570 path = path.replace(CONFIG, CONFIG1);
571 } else if (path.contains(ACTION2)) {
572 path = path.replace(ACTION, ACTION1);
573 } else if (path.contains(DECISION2)) {
574 path = path.replace(DECISION, DECISION1);
576 PolicyController controller = getPolicyControllerInstance();
577 String[] split = path.split(":");
578 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
579 SimpleBindings peParams = new SimpleBindings();
580 peParams.put(SPLIT_1, split[1]);
581 peParams.put(SPLIT_0, split[0]);
582 List<Object> queryData;
583 if (PolicyController.isjUnit()) {
584 queryData = controller.getDataByQuery(query, null);
586 queryData = controller.getDataByQuery(query, peParams);
588 if (queryData.isEmpty()) {
589 return error("Error Occured while Describing the Policy - query is empty");
591 PolicyEntity entity = (PolicyEntity) queryData.get(0);
594 temp = File.createTempFile(policyName, ".tmp");
595 } catch (IOException e) {
596 String message = "Failed to create temp file " + policyName + ".tmp";
597 LOGGER.error(message + e);
598 return error(message);
600 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
601 bw.write(entity.getPolicyData());
602 } catch (IOException e) {
603 LOGGER.error("Exception Occured while Describing the Policy" + e);
605 object = HumanPolicyComponent.DescribePolicy(temp);
607 Files.delete(temp.toPath());
608 } catch (IOException e) {
609 LOGGER.warn("Failed to delete " + temp.getName() + e);
614 // Get the List of Policies and Scopes for Showing in Editor tab
615 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
617 return processPolicyList(params, request);
618 } catch (Exception e) {
619 LOGGER.error("list", e);
620 return error(e.getMessage());
624 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
625 PolicyController controller = getPolicyControllerInstance();
626 // Get the Login Id of the User from Request
627 String testUserID = getTestUserId();
628 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
629 List<Object> userRoles = controller.getRoles(userId);
630 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
631 List<String> roles = pair.u;
632 Set<String> scopes = pair.t;
633 Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
635 List<JSONObject> resultList = new ArrayList<>();
636 String path = params.getString("path");
637 if (path.contains("..xml")) {
638 path = path.replaceAll("..xml", "").trim();
641 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
643 && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) {
644 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
646 if (!FORWARD_SLASH.equals(path)) {
647 String tempScope = path.substring(1, path.length());
648 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
649 scopes.add(tempScope);
654 if (!FORWARD_SLASH.equals(path)) {
656 String scopeName = path.substring(path.indexOf('/') + 1);
657 activePolicyList(scopeName, resultList, roles, scopes, roleByScope);
658 } catch (Exception ex) {
659 LOGGER.error("Error Occured While reading Policy Files List" + ex);
661 return new JSONObject().put(RESULT, resultList);
664 processRoles(scopes, roles, resultList, roleByScope);
666 return new JSONObject().put(RESULT, resultList);
669 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList,
670 Map<String, String> roleByScope) {
671 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
672 List<Object> scopesList = queryPolicyEditorScopes(null);
673 for (Object list : scopesList) {
674 PolicyEditorScopes scope = (PolicyEditorScopes) list;
675 if (!(scope.getScopeName().contains(File.separator))) {
676 JSONObject el = new JSONObject();
677 el.put(NAME, scope.getScopeName());
678 el.put(DATE, scope.getModifiedDate());
681 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
682 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
683 el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
684 if (!scopes.contains(scope.getScopeName())) {
690 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
691 for (Object scope : scopes) {
692 JSONObject el = new JSONObject();
693 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
694 if (!scopesList.isEmpty()) {
695 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
696 el.put(NAME, scopeById.getScopeName());
697 el.put(DATE, scopeById.getModifiedDate());
700 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
701 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
702 if (!(resultList).stream().anyMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
703 el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
711 private List<Object> queryPolicyEditorScopes(String scopeName) {
712 String scopeNamequery;
713 SimpleBindings params = new SimpleBindings();
714 if (scopeName == null) {
715 scopeNamequery = "from PolicyEditorScopes";
717 scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
718 params.put(SCOPE_NAME, scopeName + "%");
720 PolicyController controller = getPolicyControllerInstance();
721 List<Object> scopesList;
722 if (PolicyController.isjUnit()) {
723 scopesList = controller.getDataByQuery(scopeNamequery, null);
725 scopesList = controller.getDataByQuery(scopeNamequery, params);
730 // Get Active Policy List based on Scope Selection form Policy Version table
731 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
732 Set<String> scopes, Map<String, String> roleByScope) {
733 PolicyController controller = getPolicyControllerInstance();
734 String scopeName = inScopeName;
735 if (scopeName.contains(FORWARD_SLASH)) {
736 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
738 if (scopeName.contains(BACKSLASH)) {
739 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
741 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
742 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
744 SimpleBindings params = new SimpleBindings();
745 params.put(SCOPE_NAME, scopeName + "%");
747 List<Object> activePolicies;
748 List<Object> scopesList;
749 if (PolicyController.isjUnit()) {
750 activePolicies = controller.getDataByQuery(query, null);
751 scopesList = controller.getDataByQuery(scopeNamequery, null);
753 activePolicies = controller.getDataByQuery(query, params);
754 scopesList = controller.getDataByQuery(scopeNamequery, params);
756 for (Object list : scopesList) {
757 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
759 String scopeNameCheck;
760 for (Object list : activePolicies) {
761 PolicyVersion policy = (PolicyVersion) list;
762 String scopeNameValue = policy.getPolicyName().substring(0,
763 policy.getPolicyName().lastIndexOf(File.separator));
764 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
765 if (scopeName.contains(ESCAPE_BACKSLASH)) {
766 scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
768 scopeNameCheck = scopeName;
770 if (scopeNameValue.equals(scopeNameCheck)) {
771 JSONObject el = new JSONObject();
773 policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
774 el.put(DATE, policy.getModifiedDate());
775 el.put(VERSION, policy.getActiveVersion());
777 el.put(TYPE, "file");
778 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
779 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
780 String roleType = roleByScope.get(scopeNameValue);
781 if (roleType == null) {
782 roleType = roleByScope.get(ALLSCOPES);
784 el.put(ROLETYPE, roleType);
787 } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
788 JSONObject el = new JSONObject();
789 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
790 el.put(DATE, policy.getModifiedDate());
791 el.put(VERSION, policy.getActiveVersion());
793 el.put(TYPE, "file");
794 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
795 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
801 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById,
802 Map<String, String> roleByScope) {
803 String scope = scopeById.getScopeName();
804 if (scope.contains(File.separator)) {
805 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
806 if (scopeName.contains(ESCAPE_BACKSLASH)) {
807 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
809 if (scope.contains(File.separator)) {
810 scope = scope.substring(targetScope.length() + 1);
811 if (scope.contains(File.separator)) {
812 scope = scope.substring(0, scope.indexOf(File.separator));
815 if (scopeName.equalsIgnoreCase(targetScope)) {
816 JSONObject el = new JSONObject();
818 el.put(DATE, scopeById.getModifiedDate());
821 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
822 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
823 String roleType = roleByScope.get(scopeName);
824 if (roleType == null) {
825 roleType = roleByScope.get(scopeName + File.separator + scope);
826 if (roleType == null) {
827 roleType = roleByScope.get(ALLSCOPES);
830 el.put(ROLETYPE, roleType);
837 private String getUserName(String loginId) {
838 PolicyController controller = getPolicyControllerInstance();
839 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
840 if (userInfo == null) {
843 return userInfo.getUserName();
847 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
849 return handlePolicyRename(params, request);
850 } catch (Exception e) {
851 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
852 return error(e.getMessage());
856 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
857 boolean isActive = false;
858 List<String> policyActiveInPDP = new ArrayList<>();
859 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
860 String userId = UserUtils.getUserSession(request).getOrgUserId();
861 String oldPath = params.getString("path");
862 String newPath = params.getString("newPath");
863 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
864 newPath = newPath.substring(newPath.indexOf('/') + 1);
865 String checkValidation;
866 if (oldPath.endsWith(".xml")) {
867 checkValidation = newPath.replace(".xml", "");
868 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
869 checkValidation.lastIndexOf("."));
870 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
871 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
872 return error("Policy Rename Failed. The Name contains special characters.");
874 JSONObject result = policyRename(oldPath, newPath, userId);
875 if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) {
879 String scopeName = oldPath;
880 String newScopeName = newPath;
881 if (scopeName.contains(FORWARD_SLASH)) {
882 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
883 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
885 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1);
886 if (scopeName.contains(BACKSLASH)) {
887 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
888 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
890 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
891 return error("Scope Rename Failed. The Name contains special characters.");
893 PolicyController controller = getPolicyControllerInstance();
894 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
895 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
896 SimpleBindings pvParams = new SimpleBindings();
897 pvParams.put(SCOPE_NAME, scopeName + "%");
898 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
899 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
900 for (Object object : activePolicies) {
901 PolicyVersion activeVersion = (PolicyVersion) object;
902 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
903 + activeVersion.getActiveVersion() + ".xml";
904 String policyNewPath = policyOldPath.replace(oldPath, newPath);
905 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
906 if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
908 policyActiveInPDP.add(policyOldPath);
909 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
910 scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
913 boolean rename = false;
914 if (activePolicies.size() != policyActiveInPDP.size()) {
918 UserInfo userInfo = new UserInfo();
919 userInfo.setUserLoginId(userId);
920 if (policyActiveInPDP.isEmpty()) {
921 renameScope(scopesList, scopeName, newScopeName, controller);
923 renameScope(scopesList, scopeName, newScopeName, controller);
924 for (String scope : scopeOfPolicyActiveInPDP) {
925 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
926 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
927 editorScopeEntity.setUserCreatedBy(userInfo);
928 editorScopeEntity.setUserModifiedBy(userInfo);
929 controller.saveData(editorScopeEntity);
933 return error("The Following policies rename failed. Since they are active in PDP Groups"
934 + policyActiveInPDP);
940 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName,
941 PolicyController controller) {
942 for (Object object : scopesList) {
943 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
944 String scopeName = inScopeName;
945 if (scopeName.contains(BACKSLASH_8TIMES)) {
946 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
947 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
949 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
950 editorScopeEntity.setScopeName(scope);
951 controller.updateData(editorScopeEntity);
955 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
958 PolicyController controller = getPolicyControllerInstance();
960 String policyVersionName = newPath.replace(".xml", "");
961 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
962 .replace(FORWARD_SLASH, File.separator);
964 String oldpolicyVersionName = oldPath.replace(".xml", "");
965 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.'))
966 .replace(FORWARD_SLASH, File.separator);
967 String newpolicyName = newPath.replace("/", ".");
968 String[] newPolicySplit = modifyPolicyName(newPath);
970 String[] oldPolicySplit = modifyPolicyName(oldPath);
972 // Check PolicyEntity table with newPolicy Name
973 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
974 SimpleBindings policyParams = new SimpleBindings();
975 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
976 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
977 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
978 if (!queryData.isEmpty()) {
979 return error("Policy rename failed. Since, the policy with same name already exists.");
982 // Query the Policy Entity with oldPolicy Name
983 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
984 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
985 SimpleBindings params = new SimpleBindings();
986 params.put("policyEntityCheck", policyEntityCheck + "%");
987 params.put("oldPolicySplit_0", oldPolicySplit[0]);
988 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
989 if (oldEntityData.isEmpty()) {
991 "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
994 StringBuilder groupQuery = new StringBuilder();
995 groupQuery.append("FROM PolicyGroupEntity where (");
996 SimpleBindings geParams = new SimpleBindings();
997 for (int i = 0; i < oldEntityData.size(); i++) {
998 entity = (PolicyEntity) oldEntityData.get(i);
1000 groupQuery.append("policyid = :policyId");
1001 geParams.put("policyId", entity.getPolicyId());
1003 groupQuery.append(" or policyid = :policyId").append(i);
1004 geParams.put("policyId" + i, entity.getPolicyId());
1007 groupQuery.append(")");
1008 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
1009 if (!groupEntityData.isEmpty()) {
1010 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
1012 for (Object anOldEntityData : oldEntityData) {
1013 entity = (PolicyEntity) anOldEntityData;
1014 String checkEntityName = entity.getPolicyName().replace(".xml", "");
1015 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
1016 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
1017 if (checkEntityName.equals(originalPolicyName)) {
1018 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0],
1019 oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
1024 } catch (Exception e) {
1025 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
1026 return error(e.getMessage());
1030 private String[] modifyPolicyName(String pathName) {
1031 return modifyPolicyName(FORWARD_SLASH, pathName);
1034 private String[] modifyPolicyName(String separator, String pathName) {
1035 String policyName = pathName.replace(separator, ".");
1036 if (policyName.contains(CONFIG2)) {
1037 policyName = policyName.replace(CONFIG, CONFIG1);
1038 } else if (policyName.contains(ACTION2)) {
1039 policyName = policyName.replace(ACTION, ACTION1);
1040 } else if (policyName.contains(DECISION2)) {
1041 policyName = policyName.replace(DECISION, DECISION1);
1043 return policyName.split(":");
1046 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension,
1047 String oldScope, String removeoldPolicyExtension, String policyName, String newpolicyName,
1048 String oldpolicyName, String userId) {
1050 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1051 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1052 PolicyController controller = getPolicyControllerInstance();
1054 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
1055 String newPolicyNameWithoutExtension = removenewPolicyExtension;
1056 if (removeoldPolicyExtension.endsWith(".xml")) {
1057 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0,
1058 oldPolicyNameWithoutExtension.indexOf('.'));
1059 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0,
1060 newPolicyNameWithoutExtension.indexOf('.'));
1062 entity.setPolicyName(
1063 entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1064 entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1065 newScope + "." + newPolicyNameWithoutExtension));
1066 entity.setScope(newScope);
1067 entity.setModifiedBy(userId);
1069 String oldConfigurationName = null;
1070 String newConfigurationName = null;
1071 if (newpolicyName.contains(CONFIG2)) {
1072 oldConfigurationName = configEntity.getConfigurationName();
1073 configEntity.setConfigurationName(
1074 configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1075 newScope + "." + newPolicyNameWithoutExtension));
1076 controller.updateData(configEntity);
1077 newConfigurationName = configEntity.getConfigurationName();
1078 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1079 if (file.exists()) {
1080 File renamefile = new File(
1081 PolicyController.getConfigHome() + File.separator + newConfigurationName);
1082 file.renameTo(renamefile);
1084 } else if (newpolicyName.contains(ACTION2)) {
1085 oldConfigurationName = actionEntity.getActionBodyName();
1086 actionEntity.setActionBody(
1087 actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension,
1088 newScope + "." + newPolicyNameWithoutExtension));
1089 controller.updateData(actionEntity);
1090 newConfigurationName = actionEntity.getActionBodyName();
1091 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1092 if (file.exists()) {
1093 File renamefile = new File(
1094 PolicyController.getActionHome() + File.separator + newConfigurationName);
1095 file.renameTo(renamefile);
1098 controller.updateData(entity);
1100 PolicyRestController restController = new PolicyRestController();
1101 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1102 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName",
1104 versionEntity.setPolicyName(policyName);
1105 versionEntity.setModifiedBy(userId);
1106 controller.updateData(versionEntity);
1107 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1);
1108 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
1109 if (movePolicyCheck.equals(moveOldPolicyCheck)) {
1110 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1112 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1114 } catch (Exception e) {
1115 LOGGER.error(EXCEPTION_OCCURED + e);
1120 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1121 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException {
1122 String queryEntityName;
1123 PolicyController controller = getPolicyControllerInstance();
1124 PolicyEntity cloneEntity = new PolicyEntity();
1125 cloneEntity.setPolicyName(newpolicyName);
1126 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1127 String removenewPolicyExtension = inRemovenewPolicyExtension;
1128 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1129 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1130 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension,
1131 newScope + "." + removenewPolicyExtension));
1132 cloneEntity.setScope(entity.getScope());
1133 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1134 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1135 String newConfigurationName = null;
1136 if (newpolicyName.contains(CONFIG2)) {
1137 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1138 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName()
1139 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1140 queryEntityName = configurationDataEntity.getConfigurationName();
1141 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1142 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1143 configurationDataEntity.setDeleted(false);
1144 configurationDataEntity.setCreatedBy(userId);
1145 configurationDataEntity.setModifiedBy(userId);
1146 controller.saveData(configurationDataEntity);
1147 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller
1148 .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1149 cloneEntity.setConfigurationData(configEntiy);
1150 newConfigurationName = configEntiy.getConfigurationName();
1151 try (FileWriter fw = new FileWriter(
1152 PolicyController.getConfigHome() + File.separator + newConfigurationName);
1153 BufferedWriter bw = new BufferedWriter(fw)) {
1154 bw.write(configEntiy.getConfigBody());
1155 } catch (IOException e) {
1156 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1159 } else if (newpolicyName.contains(ACTION2)) {
1160 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1161 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName()
1162 .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
1163 queryEntityName = actionBodyEntity.getActionBodyName();
1164 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1165 actionBodyEntity.setDeleted(false);
1166 actionBodyEntity.setCreatedBy(userId);
1167 actionBodyEntity.setModifiedBy(userId);
1168 controller.saveData(actionBodyEntity);
1169 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class,
1170 "actionBodyName", queryEntityName);
1171 cloneEntity.setActionBodyEntity(actionEntiy);
1172 newConfigurationName = actionEntiy.getActionBodyName();
1173 try (FileWriter fw = new FileWriter(
1174 PolicyController.getActionHome() + File.separator + newConfigurationName);
1175 BufferedWriter bw = new BufferedWriter(fw)) {
1176 bw.write(actionEntiy.getActionBody());
1177 } catch (IOException e) {
1178 LOGGER.error("Exception Occured While cloning the configuration file" + e);
1183 cloneEntity.setDeleted(entity.isDeleted());
1184 cloneEntity.setCreatedBy(userId);
1185 cloneEntity.setModifiedBy(userId);
1186 controller.saveData(cloneEntity);
1188 // Notify others paps regarding clone policy.
1189 PolicyRestController restController = new PolicyRestController();
1190 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1194 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1196 String userId = UserUtils.getUserSession(request).getOrgUserId();
1197 String oldPath = params.getString("path");
1198 String newPath = params.getString("newPath");
1199 oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
1200 newPath = newPath.substring(newPath.indexOf('/') + 1);
1202 String policyVersionName = newPath.replace(".xml", "");
1203 String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1);
1204 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
1205 .replace(FORWARD_SLASH, File.separator);
1207 String newpolicyName = newPath.replace(FORWARD_SLASH, ".");
1209 String orignalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1211 String newPolicyCheck = newpolicyName;
1212 if (newPolicyCheck.contains(CONFIG2)) {
1213 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1214 } else if (newPolicyCheck.contains(ACTION2)) {
1215 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1216 } else if (newPolicyCheck.contains(DECISION2)) {
1217 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1219 if (!newPolicyCheck.contains(":")) {
1220 return error("Policy Clone Failed. The Name contains special characters.");
1222 String[] newPolicySplit = newPolicyCheck.split(":");
1224 String checkValidation = newPolicySplit[1].replace(".xml", "");
1225 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
1226 checkValidation.lastIndexOf("."));
1227 if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
1228 return error("Policy Clone Failed. The Name contains special characters.");
1231 String[] oldPolicySplit = modifyPolicyName(orignalPolicyName);
1233 PolicyController controller = getPolicyControllerInstance();
1235 PolicyEntity entity = null;
1236 boolean success = false;
1238 // Check PolicyEntity table with newPolicy Name
1239 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1240 SimpleBindings policyParams = new SimpleBindings();
1241 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1242 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1243 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1244 if (!queryData.isEmpty()) {
1245 return error("Policy already exists with same name");
1248 // Query the Policy Entity with oldPolicy Name
1249 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1250 SimpleBindings peParams = new SimpleBindings();
1251 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1252 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1253 if (PolicyController.isjUnit()) {
1254 queryData = controller.getDataByQuery(policyEntityquery, null);
1256 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1258 if (!queryData.isEmpty()) {
1259 entity = (PolicyEntity) queryData.get(0);
1261 if (entity != null) {
1262 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0],
1263 newPolicySplit[1], entity, userId);
1268 PolicyVersion entityItem = new PolicyVersion();
1269 entityItem.setActiveVersion(Integer.parseInt(version));
1270 entityItem.setHigherVersion(Integer.parseInt(version));
1271 entityItem.setPolicyName(policyName);
1272 entityItem.setCreatedBy(userId);
1273 entityItem.setModifiedBy(userId);
1274 entityItem.setModifiedDate(new Date());
1275 controller.saveData(entityItem);
1278 LOGGER.debug("copy from: {} to: {}" + oldPath + newPath);
1281 } catch (Exception e) {
1282 LOGGER.error("copy", e);
1283 return error(e.getMessage());
1287 // Delete Policy or Scope Functionality
1288 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1289 PolicyController controller = getPolicyControllerInstance();
1290 PolicyRestController restController = new PolicyRestController();
1291 PolicyEntity policyEntity = null;
1292 String policyNamewithoutExtension;
1294 String userId = UserUtils.getUserSession(request).getOrgUserId();
1295 String deleteVersion = "";
1296 String path = params.getString("path");
1297 LOGGER.debug("delete {}" + path);
1298 if (params.has("deleteVersion")) {
1299 deleteVersion = params.getString("deleteVersion");
1301 path = path.substring(path.indexOf('/') + 1);
1302 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1303 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1305 SimpleBindings policyParams = new SimpleBindings();
1306 if (path.endsWith(".xml")) {
1307 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1308 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1309 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1310 policyParams.put(SPLIT_1, split[1] + "%");
1311 policyParams.put(SPLIT_0, split[0]);
1313 policyNamewithoutExtension = path.replace(File.separator, ".");
1314 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope";
1315 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%");
1316 policyParams.put("exactScope", policyNamewithoutExtension);
1319 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1320 String activePolicyName = null;
1321 boolean pdpCheck = false;
1322 if (path.endsWith(".xml")) {
1323 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1324 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1));
1325 if ("ALL".equals(deleteVersion)) {
1326 if (!policyEntityobjects.isEmpty()) {
1327 for (Object object : policyEntityobjects) {
1328 policyEntity = (PolicyEntity) object;
1329 String groupEntityquery = "from PolicyGroupEntity where policyid ='"
1330 + policyEntity.getPolicyId() + "'";
1331 SimpleBindings pgeParams = new SimpleBindings();
1332 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1333 if (!groupobject.isEmpty()) {
1335 activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1337 // Delete the entity from Elastic Search Database
1338 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1339 restController.deleteElasticData(searchFileName);
1340 // Delete the entity from Policy Entity table
1341 controller.deleteData(policyEntity);
1342 if (policyNamewithoutExtension.contains(CONFIG2)) {
1343 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1344 + policyEntity.getConfigurationData().getConfigurationName()));
1345 controller.deleteData(policyEntity.getConfigurationData());
1346 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1347 policyEntity.getConfigurationData().getConfigurationName());
1348 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1349 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1350 + policyEntity.getActionBodyEntity().getActionBodyName()));
1351 controller.deleteData(policyEntity.getActionBodyEntity());
1352 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1353 policyEntity.getActionBodyEntity().getActionBodyName());
1358 // Policy Notification
1359 PolicyVersion versionEntity = new PolicyVersion();
1360 versionEntity.setPolicyName(policyNamewithoutExtension);
1361 versionEntity.setModifiedBy(userId);
1362 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1364 // Delete from policyVersion table
1365 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1366 getActivePDPPolicyVersion = getActivePDPPolicyVersion
1367 .substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1);
1368 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion
1369 + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='"
1370 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1371 controller.executeQuery(policyVersionQuery);
1373 "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
1374 + activePolicyName);
1376 // No Active Policy in PDP. So, deleting all entries from policyVersion table
1377 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1378 + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
1379 controller.executeQuery(policyVersionQuery);
1381 } else if ("CURRENT".equals(deleteVersion)) {
1382 String currentVersionPolicyName = policyNamewithExtension
1383 .substring(policyNamewithExtension.lastIndexOf(File.separator) + 1);
1384 String currentVersionScope = policyNamewithExtension
1385 .substring(0, policyNamewithExtension.lastIndexOf(File.separator))
1386 .replace(File.separator, ".");
1387 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1389 SimpleBindings peParams = new SimpleBindings();
1390 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1391 peParams.put("currentVersionScope", currentVersionScope);
1393 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1394 if (!policyEntitys.isEmpty()) {
1395 policyEntity = (PolicyEntity) policyEntitys.get(0);
1397 if (policyEntity == null) {
1401 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1402 SimpleBindings geParams = new SimpleBindings();
1403 geParams.put("policyEntityId", policyEntity.getPolicyId());
1404 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1405 if (!groupobject.isEmpty()) {
1406 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"
1407 + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'");
1410 // Delete the entity from Elastic Search Database
1411 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1412 restController.deleteElasticData(searchFileName);
1413 // Delete the entity from Policy Entity table
1414 controller.deleteData(policyEntity);
1415 if (policyNamewithoutExtension.contains(CONFIG2)) {
1416 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1417 + policyEntity.getConfigurationData().getConfigurationName()));
1418 controller.deleteData(policyEntity.getConfigurationData());
1419 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1420 policyEntity.getConfigurationData().getConfigurationName());
1421 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1422 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1423 + policyEntity.getActionBodyEntity().getActionBodyName()));
1424 controller.deleteData(policyEntity.getActionBodyEntity());
1425 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1426 policyEntity.getActionBodyEntity().getActionBodyName());
1430 int highestVersion = 0;
1431 if (!policyEntityobjects.isEmpty()) {
1432 for (Object object : policyEntityobjects) {
1433 policyEntity = (PolicyEntity) object;
1434 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1435 int policyEntityVersion = Integer
1436 .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1));
1437 if (policyEntityVersion > highestVersion && policyEntityVersion != version) {
1438 highestVersion = policyEntityVersion;
1443 // Policy Notification
1444 PolicyVersion entity = new PolicyVersion();
1445 entity.setPolicyName(policyNamewithoutExtension);
1446 entity.setActiveVersion(highestVersion);
1447 entity.setModifiedBy(userId);
1448 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1451 if (highestVersion != 0) {
1452 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion
1453 + "' , highest_version='" + highestVersion + "' where policy_name ='"
1454 + policyNamewithoutExtension.replace("\\", "\\\\") + "'";
1456 updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1457 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1459 controller.executeQuery(updatequery);
1461 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
1462 + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
1463 controller.executeQuery(policyVersionQuery);
1467 List<String> activePoliciesInPDP = new ArrayList<>();
1468 if (policyEntityobjects.isEmpty()) {
1469 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1470 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1471 controller.executeQuery(policyScopeQuery);
1474 for (Object object : policyEntityobjects) {
1475 policyEntity = (PolicyEntity) object;
1476 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1477 SimpleBindings geParams = new SimpleBindings();
1478 geParams.put("policyEntityId", policyEntity.getPolicyId());
1479 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1480 if (!groupobject.isEmpty()) {
1482 activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
1484 // Delete the entity from Elastic Search Database
1485 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1486 restController.deleteElasticData(searchFileName);
1487 // Delete the entity from Policy Entity table
1488 controller.deleteData(policyEntity);
1489 policyNamewithoutExtension = policyEntity.getPolicyName();
1490 if (policyNamewithoutExtension.contains(CONFIG2)) {
1491 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
1492 + policyEntity.getConfigurationData().getConfigurationName()));
1493 controller.deleteData(policyEntity.getConfigurationData());
1494 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1495 policyEntity.getConfigurationData().getConfigurationName());
1496 } else if (policyNamewithoutExtension.contains(ACTION2)) {
1497 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
1498 + policyEntity.getActionBodyEntity().getActionBodyName()));
1499 controller.deleteData(policyEntity.getActionBodyEntity());
1500 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
1501 policyEntity.getActionBodyEntity().getActionBodyName());
1505 // Delete from policyVersion and policyEditor Scope table
1506 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"
1507 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0;
1508 controller.executeQuery(policyVersionQuery);
1510 // Policy Notification
1511 PolicyVersion entity = new PolicyVersion();
1512 entity.setPolicyName(path);
1513 entity.setModifiedBy(userId);
1514 controller.watchPolicyFunction(entity, path, "DeleteScope");
1516 // Add Active Policies List to PolicyVersionTable
1517 for (String anActivePoliciesInPDP : activePoliciesInPDP) {
1518 String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
1519 int activePDPPolicyVersion = Integer
1520 .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
1521 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.'))
1522 .replace(".", File.separator);
1523 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1524 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1525 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1526 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1527 insertactivePDPVersion.setCreatedBy(userId);
1528 insertactivePDPVersion.setModifiedBy(userId);
1529 controller.saveData(insertactivePDPVersion);
1532 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"
1533 + activePoliciesInPDP);
1535 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
1536 + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
1537 controller.executeQuery(policyScopeQuery);
1542 } catch (Exception e) {
1543 LOGGER.error(DELETE, e);
1544 return error(e.getMessage());
1549 private JSONObject editFile(JSONObject params) throws ServletException {
1552 PolicyController controller = getPolicyControllerInstance();
1553 String mode = params.getString("mode");
1554 String path = params.getString("path");
1555 LOGGER.debug("editFile path: {}" + path);
1557 String domain = path.substring(1, path.lastIndexOf('/'));
1558 domain = domain.replace(FORWARD_SLASH, ".");
1560 path = path.substring(1);
1561 path = path.replace(FORWARD_SLASH, ".");
1563 String[] split = modifyPolicyName(path);
1565 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1566 SimpleBindings peParams = new SimpleBindings();
1567 peParams.put(SPLIT_1, split[1]);
1568 peParams.put(SPLIT_0, split[0]);
1569 List<Object> queryData;
1570 if (PolicyController.isjUnit()) {
1571 queryData = controller.getDataByQuery(query, null);
1573 queryData = controller.getDataByQuery(query, peParams);
1575 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1576 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1578 Object policy = XACMLPolicyScanner.readPolicy(stream);
1579 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1580 policyAdapter.setData(policy);
1582 if ("viewPolicy".equalsIgnoreCase(mode)) {
1583 policyAdapter.setReadOnly(true);
1584 policyAdapter.setEditPolicy(false);
1586 policyAdapter.setReadOnly(false);
1587 policyAdapter.setEditPolicy(true);
1590 policyAdapter.setDomainDir(domain);
1591 policyAdapter.setPolicyData(policy);
1592 String policyName = path.replace(".xml", "");
1593 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1594 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1));
1596 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1597 Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter, entity);
1599 policyAdapter.setParentPath(null);
1600 ObjectMapper mapper = new ObjectMapper();
1601 String json = mapper.writeValueAsString(policyAdapter);
1602 JsonNode jsonNode = mapper.readTree(json);
1604 return new JSONObject().put(RESULT, jsonNode);
1605 } catch (Exception e) {
1606 LOGGER.error("editFile", e);
1607 return error(e.getMessage());
1612 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1613 PolicyController controller = getPolicyControllerInstance();
1616 String userId = UserUtils.getUserSession(request).getOrgUserId();
1617 String path = params.getString("path");
1619 if (params.has(SUB_SCOPENAME)) {
1620 if (!"".equals(params.getString(SUB_SCOPENAME))) {
1621 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator
1622 + params.getString(SUB_SCOPENAME);
1625 name = params.getString(NAME);
1627 } catch (Exception e) {
1628 name = params.getString(NAME);
1629 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope" + e);
1631 String validateName;
1632 if (name.contains(File.separator)) {
1633 validateName = name.substring(name.lastIndexOf(File.separator) + 1);
1635 validateName = name;
1637 if (!name.isEmpty()) {
1638 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1639 if (!validate.contains(SUCCESS)) {
1640 return error(validate);
1643 LOGGER.debug("addFolder path: {} name: {}" + path + name);
1644 if (!"".equals(name)) {
1645 if (name.startsWith(File.separator)) {
1646 name = name.substring(1);
1648 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class,
1650 if (entity == null) {
1651 UserInfo userInfo = new UserInfo();
1652 userInfo.setUserLoginId(userId);
1653 PolicyEditorScopes newScope = new PolicyEditorScopes();
1654 newScope.setScopeName(name);
1655 newScope.setUserCreatedBy(userInfo);
1656 newScope.setUserModifiedBy(userInfo);
1657 controller.saveData(newScope);
1659 return error("Scope Already Exists");
1663 } catch (Exception e) {
1664 LOGGER.error("addFolder", e);
1665 return error(e.getMessage());
1669 // Return Error Object
1670 private JSONObject error(String msg) throws ServletException {
1672 JSONObject result = new JSONObject();
1673 result.put(SUCCESS, false);
1674 result.put("error", msg);
1675 return new JSONObject().put(RESULT, result);
1676 } catch (JSONException e) {
1677 throw new ServletException(e);
1681 // Return Success Object
1682 private JSONObject success() throws ServletException {
1684 JSONObject result = new JSONObject();
1685 result.put(SUCCESS, true);
1686 result.put("error", (Object) null);
1687 return new JSONObject().put(RESULT, result);
1688 } catch (JSONException e) {
1689 throw new ServletException(e);
1693 private PolicyController getPolicyControllerInstance() {
1694 return policyController != null ? getPolicyController() : new PolicyController();
1697 private String getTestUserId() {
1701 public static void setTestUserId(String testUserId) {
1702 PolicyManagerServlet.testUserId = testUserId;